Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: String replace index

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.

like image 619
David Davó Avatar asked Aug 09 '16 16:08

David Davó


3 Answers

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

like image 189
janbrohl Avatar answered Sep 19 '22 22:09

janbrohl


You can achieve this by doing:

yourString = "Hello"
yourIndexToReplace = 1 #e letter
newLetter = 'x'
yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))
like image 33
A Monad is a Monoid Avatar answered Sep 21 '22 22:09

A Monad is a Monoid


You can use join() with sub-strings.

s = 'cdabcjkewabcef'
sequence = '###'
indicies = (9,11)
print sequence.join([s[:indicies[0]-1], s[indicies[1]:]])
>>> 'cdabcjke###cef'
like image 27
ospahiu Avatar answered Sep 19 '22 22:09

ospahiu