在Python中更改字符串中的一个字符

2024-04-20 03:52:45 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,替换字符串中的字符最简单的方法是什么?

例如:

text = "abcdefg";
text[1] = "Z";
           ^

Tags: 方法字符串text字符abcdefg
3条回答

不要修改字符串。

将它们作为列表使用;仅在需要时才将它们转换为字符串。

>>> 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字符串是不可变的(即它们不能被修改)。这是有原因的。使用列表,直到你别无选择,然后把它们变成字符串。

最快的方法?

有三种方法。对于追求速度的人,我推荐“方法2”

方法1

由这个answer给出

text = 'abcdefg'
new = list(text)
new[6] = 'W'
''.join(new)

比“方法2”要慢得多

timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
1.0411581993103027

方法2(快速方法)

由这个answer给出

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
new = text[:1] + 'Z' + text[2:]

相关问题 更多 >