【发布时间】:2018-01-29 15:35:50
【问题描述】:
我创建了一个魔术师姓名列表。我正在尝试将“The Great”添加到列表中的每个单独项目,同时永久更改列表格式。到目前为止,这是我的代码:
magician_names = ['houdini' , 'chris angel', 'ted']
def show_magicians():
print("These are your magicians tonight.")
while magician_names:
print(magician_names)
break
show_magicians()
def make_great():
for name in magician_names:
while True:
['The Great' , name]
break
print(magician_names)
我可以创建一个 for 循环和一个字符串来打印每个单独的名称,并在其前面使用“The Great”,如下所示:
for magician in magician_names:
print("The Great " + magician)
打印这个结果:
The Great houdini
The Great chris angel
The Great ted
但是我想要它,所以当我调用函数并打印列表“magician_names”时,它会打印出列表的更改版本,格式如下:
['the great houdini' , 'the great chris angel', 'the great ted']
【问题讨论】:
-
不知道你到底在做什么,但你把一个简单的问题复杂化了。列表是 Python 中的可变数据结构,因此您需要做的就是使用字符串连接和列表迭代。
-
用 new 字符串替换列表中的每个项目,或者用新字符串创建一个新列表。
-
花点时间和the Tutorial一起练习例子。它将让您了解 Python 提供的帮助您解决问题的工具。
-
while magician_names: print(magician_names) break的意义何在?print(magician_names)也一样。
标签: python python-3.x list function