就是这样replace
工作的。它不会将“char at #”替换为“char at #”。它实际上替换了给定字符的所有出现。
当您到达时,x.replace(x[2], x[4])
您已经在x[0]
and具有相同的字符x[2]
。因此,它们都被替换为x[4]
.
看:
>>> x = "abcde"
>>> x = x.replace(x[0], x[2]) # == replace("a", "c")
>>> x
'cbcde'
>>> x = x.replace(x[2], x[4]) # == replace("c", "e")
>>> x
'ebede'
为了让您的代码正常工作,我建议这样做:
x = "abcdefghi"
x = list(x)
for i in range(len(x)):
if i < 4:
x[i] = x[i+2]
print "".join(x)
结果:
cbcdefghi
cdcdefghi
cdedefghi
cdefefghi
甚至没有迭代:
x = "abcdefghi"
x = list(x)
x[0:4] = x[2:6]
print "".join(x)
结果:
cdefefghi