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.repl
Elegant and short:
def replace_ocurrance(string,from,to,num)
strange_char = “$&$@$$&”
return string.replace(from,strange_char,num).replace(strange_char, from,num-1).replace(to, strange_char,1)
I use simple function, which lists all occurrences, picks the nth one's position and uses it to split original string into two substrings. Then it replaces first occurrence in the second substring and joins substrings back into the new string:
import re
def replacenth(string, sub, wanted, n):
where = [m.start() for m in re.finditer(sub, string)][n-1]
before = string[:where]
after = string[where:]
after = after.replace(sub, wanted, 1)
newString = before + after
print(newString)
For these variables:
string = 'ababababababababab'
sub = 'ab'
wanted = 'CD'
n = 5
outputs:
ababababCDabababab
Notes:
The
where
variable actually is a list of matches' positions, where you pick up the nth one. But list item index starts with0
usually, not with1
. Therefore there is an-1
index andn
variable is the actual nth substring. My example finds 5th string. If you usen
index and want to find 5th position, you'll needn
to be4
. Which you use usually depends on the function, which generates ourn
.
This should be the simplest way, but maybe it isn't the most Pythonic way, because the
where
variable construction needs importingre
library. Maybe somebody will find even more Pythonic way.
Sources and some links in addition:
where
construction: How to find all occurrences of a substring?- string splitting: https://www.daniweb.com/programming/software-development/threads/452362/replace-nth-occurrence-of-any-sub-string-in-a-string
- similar question: Find the nth occurrence of substring in a string
I have come up with the below, which considers also options to replace all 'old' string occurrences to the left or to the right. Naturally, there is no option to replace all occurrences, as standard str.replace works perfect.
def nth_replace(string, old, new, n=1, option='only nth'):
"""
This function replaces occurrences of string 'old' with string 'new'.
There are three types of replacement of string 'old':
1) 'only nth' replaces only nth occurrence (default).
2) 'all left' replaces nth occurrence and all occurrences to the left.
3) 'all right' replaces nth occurrence and all occurrences to the right.
"""
if option == 'only nth':
left_join = old
right_join = old
elif option == 'all left':
left_join = new
right_join = old
elif option == 'all right':
left_join = old
right_join = new
else:
print("Invalid option. Please choose from: 'only nth' (default), 'all left' or 'all right'")
return None
groups = string.split(old)
nth_split = [left_join.join(groups[:n]), right_join.join(groups[n:])]
return new.join(nth_split)
def replace_nth_occurance(some_str, original, replacement, n):
""" Replace nth occurance of a string with another string
"""
all_replaced = some_str.replace(original, replacement, n) # Replace all originals up to (including) nth occurance and assign it to the variable.
for i in range(n):
first_originals_back = all_replaced.replace(replacement, original, i) # Restore originals up to nth occurance (not including nth)
return first_originals_back
The last answer is nearly perfect - only one correction:
def replacenth(string, sub, wanted, n):
where = [m.start() for m in re.finditer(sub, string)][n - 1]
before = string[:where]
after = string[where:]
after = after.replace(sub, wanted)
newString = before + after
return newString
The after-string has to be stored in the this variable again after replacement. Thank you for the great solution!
General solution: replace any specified instance(s) of a substring [pattern] with another string.
def replace(instring,pattern,replacement,n=[1]):
"""Replace specified instance(s) of pattern in string.
Positional arguments
instring - input string
pattern - regular expression pattern to search for
replacement - replacement
Keyword arguments
n - list of instances requested to be replaced [default [1]]
"""
import re
outstring=''
i=0
for j,m in enumerate(re.finditer(pattern,instring)):
if j+1 in n: outstring+=instring[i:m.start()]+replacement
else: outstring+=instring[i:m.end()]
i=m.end()
outstring+=instring[i:]
return outstring