在Python中更改字符串中的一个字符在Python中替换字符串中的字符最简单的方法是什么?例如:text = "abcdefg";text[1] = "Z"; ^
3 回答

HUX布斯
TA贡献1876条经验 获得超6个赞
不要修改字符串。
将它们作为列表处理;只有在需要时才将它们转换为字符串。
>>> s = list("Hello zorld")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[6] = 'W'
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello World'
Python字符串是不可变的(即它们不能被修改)。确实有很多原因何在。在没有选择之前使用列表,然后再将它们转换为字符串。

慕容708150
TA贡献1831条经验 获得超4个赞
最快的方法?
方法1
text = 'abcdefg'new = list(text)new[6] = 'W'''.join(new)
timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)1.0411581993103027
方法2(快速法)
text = 'abcdefg'text = text[:1] + 'Z' + text[2:]
timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)0.34651994705200195
方法3:
timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)1.0387420654296875

慕工程0101907
TA贡献1887条经验 获得超5个赞
text = "Z" + text[1:]
text = text[:1] + "Z" + text[2:]
添加回答
举报
0/150
提交
取消