I would like to add a string (not replace) based on the nth occurence of multiple strings.
Example:
tablespecs = "l c d r c l"
Now assuming I want to add the third appearance of l, c and r the string "here: ", the desired output should be:
desired_tablespecs = "l c d here: r c l"
So solely considering l, c and r, ignoring d.
I solely cames as close, as the following, instead of adding the copde the code replaces the match, so it delivers "l c d here: c l".
tablespecs = "l c d r c l"
def replacenth(string, sub, wanted, n):
pattern = re.compile(sub)
where = [m for m in pattern.finditer(string)][n-1]
before = string[:where.start()]
after = string[where.end():]
newString = before + wanted + after
return newString
#Source of code chunk https://stackoverflow.com/questions/35091557/replace-nth-occurrence-of-substring-in-string
replacenth(tablespecs, "[lcr]", "[here:]", 3)
#wrong_output: 'l c d [here:] c l'