Python 为什么不是';字符串值是否已更新?

Python 为什么不是';字符串值是否已更新?,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[stri

我正在编写一个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'

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

在第一种情况下,
字符串
不会被分配回
列表
。因此,当您打印
列表中的元素时,似乎没有任何变化。在第二种情况下,每个元素都用
\n
更新。啊,我明白了-谢谢。我的第二个解决方案是实现这一点的最简单方法吗?