change only the nth occurrence of a pattern in a string

Roy Smith roy at
Wed Dec 31 16:23:05 CET 2008

In article <0scs26-7a5.ln1 at>,
 TP <Tribulations at Paralleles.invalid> wrote:

> Hi everybody,
> I would like to change only the nth occurence of a pattern in a string.

It's a little ugly, but the following looks like it works.  The gist is to 
split the string on your pattern, then re-join the pieces using the 
original delimiter everywhere except for the n'th splice.  Split() is a 
wonderful tool.  I'm a hard-core regex geek, but I find that most things I 
might have written a big hairy regex for are easier solved by doing split() 
and then attacking the pieces.

There may be some fencepost errors here.  I got the basics working, and 
left the details as an exercise for the reader :-)

This version assumes the pattern is a literal string.  If it's really a 
regex, you'll need to put the pattern in parens when you call split(); this 
will return the exact text matched each time as elements of the list.  And 
then your post-processing gets a little more complicated, but nothing 
that's too bad.

This does a couple of passes over the data, but at least all the operations 
are O(n), so the whole thing is O(n).


import re

v = "coucoucoucou"

pattern = "o"
n = 2
parts = re.split(pattern, v)
print parts

first = parts[:n]
last = parts[n:]
print first
print last

j1 = pattern.join(first)
j2 = pattern.join(last)
print j1
print j2
print "i".join([j1, j2])
print v

More information about the Python-list mailing list