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

例如:

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

当前回答

不要修改字符串。

将它们作为列表来处理;只在需要时将它们转换为字符串。

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

其他回答

试试这个:

old_string = "mba"
string_list = list(old_string)
string_list[2] = "e"
//Replace 3rd element

new_string = "".join(string_list)

print(new_string)

正如其他人所说,通常Python字符串应该是不可变的。

但是,如果你使用的是CPython (python.org上的实现),则可以使用ctypes来修改内存中的字符串结构。

下面是我使用该技术清除字符串的示例。

在python中将数据标记为敏感

为了完整起见,我提到了这一点,这应该是您最后的手段,因为它很粗糙。

如果你的世界是100% ascii/utf-8(很多用例适合这个盒子):

b = bytearray(s, 'utf-8')
# process - e.g., lowercasing: 
#    b[0] = b[i+1] - 32
s = str(b, 'utf-8')

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

我喜欢f弦:

text = f'{text[:1]}Z{text[2:]}'

在我的机器中,这种方法比使用+来连接字符串的“快速方法”快10%:

>>> timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
1.1691178000000093
>>> timeit.timeit("text = 'abcdefg'; text = f'{text[:1]}Z{text[2:]}'", number =1000000)
0.9047831999999971
>>>