Python:字符串替换索引 [英] Python: String replace index

查看:54
本文介绍了Python:字符串替换索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的意思是,我想将 str[9:11] 替换为另一个字符串.如果我做 str.replace(str[9:11], "###") 不行,因为序列 [9:11] 可以多次出现.如果 str 是 "cdabcjkewabcef" 我会得到 "cd###jkew###ef" 但我只想替换第二个.

I mean, i want to replace str[9:11] for another string. If I do str.replace(str[9:11], "###") It doesn't work, because the sequence [9:11] can be more than one time. If str is "cdabcjkewabcef" i would get "cd###jkew###ef" but I only want to replace the second.

推荐答案

你可以做到

s="cdabcjkewabcef"
snew="".join((s[:9],"###",s[12:]))

这应该比在大字符串上加入 snew=s[:9]+"###"+s[12:] 更快

which should be faster than joining like snew=s[:9]+"###"+s[12:] on large strings

这篇关于Python:字符串替换索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆