这里我们修改字符串s
在循环时:
s = 'hello'
for c in s:
s += c
print(s)
它不会产生无限循环(它可以:我们在每次迭代中添加一个新字符!)。
多年来我就知道这一点,但我无法真正解释原因。这与字符串不变性有关还是无关?
做的时候
for c in s:
, 是原版s
在开始循环之前复制到内存中? 我认为可能会产生无限循环的另一种情况,但它不会:
s = 'hello'
def f(x):
i = 0
while True:
try:
yield x[i]
except IndexError:
break
i += 1
for c in f(s):
s += c
print(s)
最佳答案
It doesn't generate an infinite loop (it could: we add a new character in each iteration!).
这是因为strings在 Python 中是不可变的。
当您这样做时
for c in s
, for
循环遍历原始对象(包含 "hello"
的对象)以及当您执行 s += c
时,创建了一个新字符串,因此,您不会修改 for
的原始字符串对象。循环仍在迭代。另外,在我的回答中添加 @Steven Rumbalski 的评论:
It iterates over the original object. Rebinding the name to a new object doesn't change the for-loop because it doesn't resolve the name on each iteration.
现在,让我们谈谈你的第二个例子:
如果你调用你的函数
f(s)
, 使其成为正式论证 x
指向包含字符串“hello”的对象,并使用字符串对象创建一个生成器。现在,随后重新分配字符串 s
(使用 s += c
)实际上创建了另一个字符串并且不会影响原始对象。你的函数的形式参数仍然指向一个包含 "hello"
的对象。 .因此,在第二个示例中对 for 循环进行第一次迭代后:
f(x)
将仍然指向一个包含“hello”的对象。 "helloh"
的对象. 重要提示:
但是,如果您尝试使用可变数据类型编写代码,则可能会创建无限循环。看到这个:
li = [ 1, 2, 3, 4 ]
for i in li:
li.append(i)
print(li)
关于python - 循环时修改字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61191364/