通过索引在python中使用replace()方法
发布时间:2020-12-20 11:53:27 所属栏目:Python 来源:网络整理
导读:参见英文答案 Python: String replace index????????????????????????????????????5个 我想做这样的事情. example_string = "test"print(example_string.replace(example_string[0],"b")) 期待输出 best 但是因为字母“t”被传递到方法中,所以最后的t也被替
参见英文答案 >
Python: String replace index????????????????????????????????????5个
我想做这样的事情. example_string = "test" print(example_string.replace(example_string[0],"b")) 期待输出 best 但是因为字母“t”被传递到方法中,所以最后的t也被替换为“b”.导致输出 besb 如何以一种导致输出“最佳”而不是“besb”的方式来实现? 解决方法
问题是.replace(old,new)返回一个字符串的副本,其中old的出现已被new替换.
相反,你可以使用以下方法交换索引i处的字符: new_str = old_str[:i] + "b" + old_str[i+1:] (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |