I want to replace the n'th occurrence of a substring in a string.
There's got to be something equivalent to what I WANT to do which is
mystring.replace("substring", 2nd)
What is the simplest and most Pythonic way to achieve this?
Why not duplicate: I don't want to use regex for this approach and most of answers to similar questions I found are just regex stripping or really complex function. I really want as simple as possible and not regex solution.
replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.
To find the index of nth occurrence of a substring in a string you can use String. indexOf() function. A string, say str2 , can occur in another string, say str1 , n number of times. There could be a requirement in your Java application, that you have to find the position of the nth occurrence of str2 in str1 .
You can use a while loop with str.find to find the nth occurrence if it exists and use that position to create the new string:
def nth_repl(s, sub, repl, n):     find = s.find(sub)     # If find is not -1 we have found at least one match for the substring     i = find != -1     # loop util we find the nth or we find no match     while find != -1 and i != n:         # find + 1 means we start searching from after the last match         find = s.find(sub, find + 1)         i += 1     # If i is equal to n we found nth match so replace     if i == n:         return s[:find] + repl + s[find+len(sub):]     return s   Example:
In [14]: s = "foobarfoofoobarbar"  In [15]: nth_repl(s, "bar","replaced",3) Out[15]: 'foobarfoofoobarreplaced'  In [16]: nth_repl(s, "foo","replaced",3) Out[16]: 'foobarfooreplacedbarbar'  In [17]: nth_repl(s, "foo","replaced",5) Out[17]: 'foobarfoofoobarbar' 
                        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