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

2024-04-24 20:11:10 发布

您现在位置: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'

我不明白为什么只有第二个有效-有人能帮我解释一下吗?你知道吗

还有,有没有更好的办法?你知道吗


Tags: 方法字符串in列表forstringlenif
1条回答
网友
1楼 · 发布于 2024-04-24 20:11:10

由于string是一个不可变的对象,在下面的代码中:

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

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

相关问题 更多 >