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.
-
1Using 'string.replace' converts every occurrence of the given text to the text you input. You are not wanting to do this, you just want to replace the text based on its position (index), not based on its contents.Luke– Luke2016-08-09 17:37:03 +00:00Commented Aug 9, 2016 at 17:37
Add a comment
|
6 Answers
str = "cdabcjkewabcef"
print((str[::-1].replace('cba','###',1))[::-1])
1 Comment
Perry
This would be a better answer if you explained how the code you provided answers the question.
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