change only the nth occurrence of a pattern in a string
apardon at forel.vub.ac.be
Mon Jan 12 12:18:53 CET 2009
On 2008-12-31, TP <Tribulations at Paralleles.invalid> wrote:
> Hi everybody,
> I would like to change only the nth occurence of a pattern in a string. The
> problem with "replace" method of strings, and "re.sub" is that we can only
> define the number of occurrences to change from the first one.
>>>> import re
>>>> re.sub( "o", "i", v,2)
>>>> re.sub( "o", "i", v,1)
> What is the best way to change only the nth occurence (occurrence number n)?
> Why this default behavior? For the user, it would be easier to put re.sub or
> replace in a loop to change the first n occurences.
I would do it as follows:
1) Change the pattern n times to somethings that doesn't occur in your string
2) Change it back n-1 times
3) Change the remaining one to what you want.
>>> v.replace('o', 'O', 2).replace('O', 'o', 1).replace('O', 'i')
More information about the Python-list