在索引中使用python中的replace()方法

Osc*_*son 3 python replace

我想做这样的事情.

example_string = "test"
print(example_string.replace(example_string[0], "b"))
Run Code Online (Sandbox Code Playgroud)

期待输出

best
Run Code Online (Sandbox Code Playgroud)

但是因为字母"t"被传递到方法中,所以最后的t也被替换为"b".导致输出

besb
Run Code Online (Sandbox Code Playgroud)

如何以一种导致输出"最佳"而不是"besb"的方式来实现?

nbr*_*ans 6

问题是.replace(old, new)返回old已替换出现的字符串的副本new.

相反,您可以i使用以下命令交换索引处的字符:

new_str = old_str[:i] + "b" + old_str[i+1:]
Run Code Online (Sandbox Code Playgroud)


dsh*_*dsh 5

检查文档

您可以使用

example_string.replace(example_string[0], "b", 1)
Run Code Online (Sandbox Code Playgroud)

尽管使用切片来替换第一个字符会更自然,正如 @nbryans 在评论中指出的那样。

  • 这适用于这种情况,但是如果您想替换“example_string[3]”怎么办? (2认同)

Mic*_*ael 1

example_string.replace("t", "b", 1)
Run Code Online (Sandbox Code Playgroud)

  • 这适用于这种情况,但是如果您想替换“example_string[3]”怎么办? (3认同)