Skip to main content
 首页 » 编程设计

python之为什么不更新字符串值

2024年10月17日32落叶

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

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

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

请您参考如下方法:

由于string是一个不可变对象(immutable对象),在这段代码中:

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

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