1

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'
NDel
  • 138
  • 10

2 Answers2

1

You can set after to start at where.start() instead of where.end(), so that it includes that character.

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.start():]
    newString = before + wanted + after
    return newString

replacenth(tablespecs, "[lcr]", "here: ", 3) 

This outputs 'l c d here: r c l'.

Ollie
  • 1,641
  • 1
  • 13
  • 31
  • Great! Many thanks for your solution. Works very well. Would you also have a solution at hand, in case n is not solely one number. So if for example the first and third occurrence shall be identified with the output ' here: l c d here: r c l'? – NDel Oct 31 '19 at 16:38
1

A slightly different approach:

tablespecs = "l c d r c l"


def replacenth(string, sub, wanted, n):
    count = 0
    out = ""

    for c in string:
        if c in sub:
            count += 1

        if count == n:
            out += wanted
            count = 0
        out += c
    return out


res = replacenth(tablespecs, "lcr", "here: ", 3)
assert res == "l c d here: r c l", res
mpawlak
  • 199
  • 1
  • 4