change only the nth occurrence of a pattern in a string

MRAB google at mrabarnett.plus.com
Wed Jan 14 17:08:39 EST 2009


Antoon Pardon wrote:
 > 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.
 >>
 >>>>> v="coucou"
 >>>>> v.replace("o","i",2)
 >> 'ciuciu'
 >>>>> import re
 >>>>> re.sub( "o", "i", v,2)
 >> 'ciuciu'
 >>>>> re.sub( "o", "i", v,1)
 >> 'ciucou'
 >>
 >> 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="coucou"
 >>>> v.replace('o', 'O', 2).replace('O', 'o', 1).replace('O', 'i')
 > 'couciu'
 >
Sorry for the last posting, but it did occur to me that str.replace()
could grow another parameter 'start', so it would become:

     s.replace(old, new[[, start], end]]) -> string

(In Python 2.x the method doesn't accept keyword arguments, so that
isn't a problem.)

If the possible replacements are numbered from 0, then 'start' is the
first one actually to perform and 'end' the one after the last to perform.

The 2-argument form would be s.replace(old, new) with 'start' defaulting
to 0 and 'end' to None => replacing all occurrences, same as now.

The 3-argument form would be s.replace(old, new, end) with 'start'
defaulting to 0 => equivalent to replacing the first 'end' occurrences,
same as now.

The 4-argument form would be s.replace(old, new, start, end) =>
replacing from the 'start'th to before the 'end'th occurrence,
additional behaviour as requested.



More information about the Python-list mailing list