3 回答

TA贡献1773条经验 获得超3个赞
在Python中,字符串是不可变的,因此您不能就地更改其字符。
但是,您可以执行以下操作:
for i in str:
srr += i
起作用的原因是它是以下操作的快捷方式:
for i in str:
srr = srr + i
上面的代码在每次迭代时都会创建一个新字符串,并将对该新字符串的引用存储在中srr。

TA贡献1807条经验 获得超9个赞
其他答案是正确的,但您当然可以执行以下操作:
>>> str1 = "mystring"
>>> list1 = list(str1)
>>> list1[5] = 'u'
>>> str1 = ''.join(list1)
>>> print(str1)
mystrung
>>> type(str1)
<type 'str'>
如果您真的想要。

TA贡献1815条经验 获得超10个赞
如aix所述-Python中的字符串是不可变的(您不能就地更改它们)。
您要尝试执行的操作可以通过多种方式完成:
# Copy the string
foo = 'Hello'
bar = foo
# Create a new string by joining all characters of the old string
new_string = ''.join(c for c in oldstring)
# Slice and copy
new_string = oldstring[:]
添加回答
举报