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

例如:

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

当前回答

最快的方法?

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

方法1

由这个答案给出

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

方法二(快速法)

由这个答案给出

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

其他回答

替换字符串中的一个字符

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

方法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:]

从python 2.6和python 3开始,你可以使用可变的bytearrays(可以像字符串那样按元素改变):

s = "abcdefg"
b_s = bytearray(s)
b_s[1] = "Z"
s = str(b_s)
print s
aZcdefg

编辑:将str改为s

edit2:正如Two-Bit Alchemist在评论中提到的,这段代码不能使用unicode。

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

更改文本功能。

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

在单行if语句中结合find和replace方法的解决方案可以是:

```python
my_var = "stackoverflaw"
my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
print(f"my_var = {my_var}")           # my_var = stackoverflaw
print(f"my_new_var = {my_new_var}")   # my_new_var = stackoverflow
```

试试这个:

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

new_string = "".join(string_list)

print(new_string)