<分区>
我想做这样的事情。
example_string = "test"
print(example_string.replace(example_string[0], "b"))
期待输出
best
然而,因为字母“t”被传递到方法中,最后的 t 也被替换为“b”。导致输出
besb
我如何以导致输出“best”而不是“besb”的方式做到这一点?
<分区>
我想做这样的事情。
example_string = "test"
print(example_string.replace(example_string[0], "b"))
期待输出
best
然而,因为字母“t”被传递到方法中,最后的 t 也被替换为“b”。导致输出
besb
我如何以导致输出“best”而不是“besb”的方式做到这一点?
最佳答案
问题是 .replace(old, new)
返回字符串的副本,其中出现的 old
已替换为 new
.
相反,您可以使用以下方式交换索引 i
处的字符:
new_str = old_str[:i] + "b" + old_str[i+1:]
关于python - 通过索引在 python 中使用 replace() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38860507/