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.
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
You can achieve this by doing:
yourString = "Hello"
yourIndexToReplace = 1 #e letter
newLetter = 'x'
yourStringNew="".join((yourString[:yourIndexToReplace],newLetter,yourString[yourIndexToReplace+1:]))
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With