Search code examples
pythonstringreplacereverse

How to replace some characters from the end of a string?


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 x. Suppose there is a method called replace_last:

>>> replace_last(s, '2', 'x')
'1231x3'

Is there any built-in or easy method to do this?


It's similar to python's str.replace():

>>> s.replace('2', 'x', 1)
'1x3123'

But it's from the end to beginning.


Solution

  • This is exactly what the rpartition function is used for:

    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