Search code examples
pythonpython-3.xstringreplacesubstring

Replacing a specific item in a string when that item occurs more than once, in Python


Let's say I have the following:

str1='restart'

I want to replace 'r' with '#' but only the second occurrence of 'r' and not the first, using the function replace()

Expected return is:

str1='resta#t'

I know how to replace either all the occurrences of 'r' str1.replace('r','#'), or a number of occurrences of 'r' starting from the first one str1.replace('r','#',1), but cannot figure how to replace just the second occurrence and not the other ones.


Solution

  • The following code does the trick.

    string = "restart"
    result = string.replace("r", "#").replace("#", "r", 1)
    print(result) # resta#t