How to replace the some characters from the end of a string?
Using regular expression function re.sub
to replace words at end of string
import re
s = "123123"
s = re.sub('23$', 'penguins', s)
print s
Prints:
1231penguins
or
import re
s = "123123"
s = re.sub('^12', 'penguins', s)
print s
Prints:
penguins3123
>>> s = "aaa bbb aaa bbb"
>>> s[::-1].replace('bbb','xxx',1)[::-1]
'aaa bbb aaa xxx'
For your second example
>>> s = "123123"
>>> s[::-1].replace('2','x',1)[::-1]
'1231x3'
This is one of the few string functions that doesn't have a left and right version, but we can mimic the behaviour using some of the string functions that do.
>>> s = '123123'
>>> t = s.rsplit('2', 1)
>>> u = 'x'.join(t)
>>> u
'1231x3'
or
>>> 'x'.join('123123'.rsplit('2', 1))
'1231x3'
This is exactly what the rpartition
function is used for:
rpartition(...) S.rpartition(sep) -> (head, sep, tail)
Search for the separator sep in S, starting at the end of S, and return the part before it, the separator itself, and the part after it. If the separator is not found, return two empty strings and S.
I wrote this function showing how to use rpartition
in your use case:
def replace_last(source_string, replace_what, replace_with):
head, _sep, tail = source_string.rpartition(replace_what)
return head + replace_with + tail
s = "123123"
r = replace_last(s, '2', 'x')
print r
Output:
1231x3