python - 如何修改数组中的字符串?

标签 python arrays function

<分区>

我想创建一个函数,在数组中的每个字符串前面添加一个特定的单词。最后我想改变数组。我有这段代码:

def make_great(magicians):
    """Change magicians"""
    for magician in magicians:
        magician = "the Great" + magician


magicians = ["hudini", "angel", "teller", "anderson", "copperfield"]
make_great(magicians)
print(magicians)

此代码不会更改数组。我怎样才能让我的功能发挥作用?

最佳答案

您可以使用enumerate 循环遍历包含索引和值的列表,然后使用索引将值直接更改到列表中:

def make_great(magicians):
    for index, magician in enumerate(magicians):
        magicians[index] = "the Great " + magician

关于python - 如何修改数组中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38084443/

相关文章:

arrays - 访问字典中的数组 (swift)

c - 在函数 C 中打开文件的问题

python - sys.exit(0) 是退出/终止 python 线程的有效方法吗?

python - 使用 python 驱动程序在 Neo4j 中创建多个节点的最佳方法

javascript - 使用顺序 for 循环遍历关联数组

javascript - 销毁对象的嵌套数组 javascript

javascript object.function 通过变量调用

php - 我如何将此示例 if else 语句转换为数组以用作 echo 语句/函数?

python - Pandas:基于字典分割和编辑文件

python - 无法使用正则表达式获得自定义结果