Issue
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.
Solution
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
Answered By - aleskva
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.