python - 为什么字符串值没有更新?

标签 python

我正在编写一个 for 循环,它将获取一个字符串列表,并在字符串末尾添加一个新行(如果还没有)。

我的第一个想法如下,但行不通:

for string in list :
    if not string.endswith('\n'):
         string += '\n'

然后我想出了下面的方法,它成功了:

for string in range(len(ist)):
    if not list[string].endswith('\n'):
        list[string] += '\n'

我很困惑为什么只有第二个有效 - 有人可以帮忙解释一下吗?

另外,有没有更好的方法来做到这一点?

最佳答案

由于字符串是一个不可变的对象,因此在这段代码中:

for string in list :
    if not string.endswith('\n'):
         string += '\n'

在每次迭代中,string 变量都会在 list 中分配一个元素,然后在列表中使用 '\n' 创建一个新字符串。结束,但这个新字符串永远不会更新回列表中。

关于python - 为什么字符串值没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37720619/

相关文章:

Python/Django 查询 - 将原始 SQL 附加到模型对象

python - ImportError:在setup.py中使用setuptools时,libSM.so.6

LAB和灰度之间的Python OpenCV色彩空间差异

python - 在python中打印表面拟合方程

python - 如何在字符串中获取给定名称的变量的值?

python - PyPy 明显比 CPython 慢

python - 如何在scala中启动 "python.exe"作为子进程?

python从两个列表中创建一个新列表,第二个列表表示重复第一个列表中的元素多少次

python - 属性错误 : 'SigSafeLogger' object has no attribute 'logger'

python - 在 pyhook Pumpmessages 中使用自己的代码