python - 通过索引替换 python 列表中的项目..失败?

标签 python list python-2.7 indexing

知道为什么我打电话时:

>>> 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/

相关文章:

python - 将Python代码的输出写入Excel中的多行

python - 从词典列表到词典

python - 如何通过拆分 python 中的列表元素来创建列表?

python - 从一行中获取特定的字符串

python - 弹性云-无法创建索引

python - 在 wxPython 中引发 wx.EVT_CLOSE 后如何阻止窗口关闭?

python - 如何在 Python 中播放声音?

字典或列表操作的 Python 命名约定

python - Python 中的实时输出

python-2.7 - 如何在pandas中获取整个数据帧的最大值