change only the nth occurrence of a pattern in a string
TP
Tribulations at Paralleles.invalid
Wed Dec 31 09:40:32 EST 2008
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.
Thanks
Julien
--
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.\
9&1+,\'Z4(55l4('])"
"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
More information about the Python-list
mailing list