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

例如:

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

当前回答

替换字符串中的一个字符

你可以使用以下任何一种方法:

方法1

一般来说,

string = f'{string[:index]}{replacing_character}{string[index+1:]}'

Here

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

方法2

一般来说,

string = string[:index] + replacing_character + string[index+1:]

在这里,

text = text[:1] + 'Z' + text[2:]

其他回答

不要修改字符串。

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

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

new = text[:1] + 'Z' + text[2:]

替换字符串中的一个字符

你可以使用以下任何一种方法:

方法1

一般来说,

string = f'{string[:index]}{replacing_character}{string[index+1:]}'

Here

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

方法2

一般来说,

string = string[:index] + replacing_character + string[index+1:]

在这里,

text = text[:1] + 'Z' + text[2:]

试试这个:

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

new_string = "".join(string_list)

print(new_string)

这个代码不是我的。我不记得是在哪里拍的。有趣的是,您可以使用它来用一个或多个字符替换一个或多个字符。 虽然这个回复很晚,但像我这样的新手(任何时候)可能会发现它很有用。

更改文本功能。

mytext = 'Hello Zorld'
# change all Z(s) to "W"
while "Z" in mytext:
      # replace "Z" to "W"
      mytext = mytext.replace('Z', 'W')
print(mytext)