循环时修改字符串

Bas*_*asj 6 python string loops immutability

在这里,我们s在循环时修改字符串:

s = 'hello'
for c in s:
    s += c
    print(s)
Run Code Online (Sandbox Code Playgroud)

它不会产生无限循环(它可以:我们在每次迭代中添加一个新字符!)。

多年来我就知道这一点,但我无法真正解释原因。这与字符串不变性有关还是无关?

执行时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)
Run Code Online (Sandbox Code Playgroud)

小智 0

这不是递归方法。完全没问题。它只会运行一次,因为您传递了一个字符串,f('hello')现在循环有“hello”要迭代。所以它只会运行一次