I want to replace characters at the end of a python string. I have this string:
s = \"123123\"
I want to replace the last 2
with
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
Here is a solution based on a simplistic interpretation of your question. A better answer will require more information.
>>> s = "aaa bbb aaa bbb"
>>> separator = " "
>>> parts = s.split(separator)
>>> separator.join(parts[:-1] + ["xxx"])
'aaa bbb aaa xxx'
Update
(After seeing edited question) another very specific answer.
>>> s = "123123"
>>> separator = "2"
>>> parts = s.split(separator)
>>> separator.join(parts[:-1]) + "x" + parts[-1]
'1231x3'
Update 2
There is far better way to do this. Courtesy @mizipzor.
For the second example, I would recommend rsplit
, as it is very simple to use and and directly achieves the goal. Here is a little function with it:
def replace_ending(sentence, old, new):
if sentence.endswith(old):
i = sentence.rsplit(old,1)
new_sentence =new.join(i)
return new_sentence
return sentence
print(replace_ending("aaa bbb aaa bbb", "bbb", "xxx"))
Output:
aaa bbb aaa xxx
I got a tricky answer, but it is not efficient enough
>>> fname = '12345.png.pngasdfg.png'
>>> suffix = '.png'
>>> fname_rev = fname[::-1]
>>> suffix_rev = suffix[::-1]
>>> fullname_rev = fname_rev.replace(suffix_rev, '', 1)
>>> fullname = fullname_rev[::-1]
>>> fullname '12345.png.pngasdfg'
Built-in function replace() takes three arguments
str.replace(old, new, max_time)
So you can delete the last mached string from the origional string
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
>>> 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'