用索引替换python列表中的项目..失败?

Jam*_*mus 2 python indexing list python-2.7

知道为什么我打电话的时候:

>>> hi = [1, 2]
>>> hi[1]=3
>>> print hi
[1, 3]
Run Code Online (Sandbox Code Playgroud)

我可以通过索引更新列表项,但是当我调用时:

>>> phrase = "hello"
>>> for item in "123":
>>>     list(phrase)[int(item)] = list(phrase)[int(item)].upper()
>>> print phrase
hello
Run Code Online (Sandbox Code Playgroud)

它失败?

应该 hELLo

Ter*_*ryA 9

你还没有初始化phrase(list你打算制作)变量.所以你几乎已经在每个循环中创建了一个列表,它完全相同.

如果您打算实际更改字符phrase,那就是不可能,就像在python中一样,字符串是不可变的.

也许make 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
Run Code Online (Sandbox Code Playgroud)