这可能是一个简单的问题,但由于某种原因,我一直在努力解决这个问题。
以下是使用print((时正常工作的示例代码:
animal = "cat"
food = "bread"
day = "Monday"
print("The", animal, "ate", food, "on", day)
它具有所需的输出:
The cat ate bread on Monday
但是,当我将其设置为变量时:
animal = "cat"
food = "bread"
day = "Monday"
sentence = ("The", animal, "ate", food, "on", day)
print(sentence)
输出为:
('The', 'cat', 'ate', 'bread', 'on', 'Monday')
我试图转换成字符串,以及文本替换,但没有成功。非常感谢您的帮助!
当您调用print("The", animal, "ate", food, "on", day)
时,您正在调用内置的Python3print()
函数。默认情况下,此函数在提供给它的每个参数之间添加空格
另一方面,当您调用sentence = ("The", animal, "ate", food, "on", day)
时,实际上是在创建一个名为tuple
的数据结构(它类似于列表(。请参阅Python 3文档中的更多信息。
要将元组中的所有元素放入字符串中,可以使用" ".join(sentence)
。这将获取元组的元素并将它们连接起来,通过提供的字符串(在本例中为空格字符(分隔每个元素。
请注意,您可以使用join()
通过任何您喜欢的字符串来分隔元素!例如,"||".join( ("What", "a", "nice", "day!") )
将把元组连接到字符串What||a||nice||day!
中。
试着这样制作sentence
-sentence = ("The " + animal + " ate " + food + " on " + day)
而不是">、";尝试使用">+";用于级联