Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

nth substring multiplicity using itertools

$
0
0

I am trying to write a function that returns a string with the nth substring replaced by a new substring.

I tried the following:

import refrom itertools import counttext = "Hello_Dear_Today_is_Nice_Today_is_Nice"def replace_nth(text, sub, rep_sub, n):    c = count(0)    res = re.sub(r"{}".format(sub), lambda x: rep_sub if next(c) == n else x.group(), text)    return resprint(replace_nth(text, "Today", "Today_2", 2))

But the returned string is the same, what am I doing wrong?

I am expecting:

Hello_Dear_Today_is_Nice_Today_2_is_Nice as a result


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>