知道为什么我打电话时:
>>> hi = [1, 2]
>>> hi[1]=3
>>> print hi
[1, 3]
我可以通过索引更新列表项,但是当我调用时:
>>> phrase = "hello"
>>> for item in "123":
>>> list(phrase)[int(item)] = list(phrase)[int(item)].upper()
>>> print phrase
hello
失败了?
应该是hELLo
最佳答案
您还没有将 phrase
(您打算创建的 list
)初始化为变量。您几乎在每个循环中都创建了一个列表,它完全相同。
如果您打算实际更改 phrase
的字符,那是不可能的,因为在 python 中,字符串是不可变的。
也许可以制作 phraselist = list(phrase)
,然后在 for 循环中编辑列表。此外,您可以使用 range()
:
>>> phrase = "hello"
>>> phraselist = list(phrase)
>>> for i in range(1,4):
... phraselist[i] = phraselist[i].upper()
...
>>> print ''.join(phraselist)
hELLo
关于python - 通过索引替换 python 列表中的项目..失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16916013/