Python:字符串替换索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38856180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: String replace index
提问by David Davó
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.
我的意思是,我想替换str[9:11]
另一个字符串。如果我这样做str.replace(str[9:11], "###")
它不起作用,因为序列 [9:11] 可以不止一次。如果 str 是"cdabcjkewabcef"
我会得到"cd###jkew###ef"
但我只想替换第二个。
回答by janbrohl
you can do
你可以做
s="cdabcjkewabcef"
snew="".join((s[:9],"###",s[12:]))
which should be faster than joining like snew=s[:9]+"###"+s[12:]
on large strings
这应该比snew=s[:9]+"###"+s[12:]
在大字符串上加入要快
回答by Damián Rafael Lattenero
You can achieve this by doing:
您可以通过执行以下操作来实现此目的:
yourString = "Hello"
yourIndexToReplace = 1 #e letter
newLetter = 'x'
yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))
回答by veerabhadra butte
str = "cdabcjkewabcef"
print((str[::-1].replace('cba','###',1))[::-1])
回答by Israel Unterman
Given txt and s - the string you want to replace:
给定 txt 和 s - 要替换的字符串:
txt.replace(s, "***", 1).replace(s, "###").replace("***", s)
Another way:
其它的办法:
txt[::-1].replace(s[::-1], "###", 1)[::-1]
回答by ospahiu
You can use join()
with sub-strings.
您可以使用join()
子字符串。
s = 'cdabcjkewabcef'
sequence = '###'
indicies = (9,11)
print sequence.join([s[:indicies[0]-1], s[indicies[1]:]])
>>> 'cdabcjke###cef'
回答by User_Targaryen
Here is a sample code:
这是一个示例代码:
word = "astalavista"
index = 0
newword = ""
addon = "xyz"
while index < 8:
newword = newword + word[index]
index += 1
ind = index
i = 0
while i < len(addon):
newword = newword + addon[i]
i += 1
while ind < len(word):
newword = newword + word[ind]
ind += 1
print newword