def replace2(astr, regex, repl, case=0, count=0):
"""
Replace all regex matches in a string with repl.
case=0 is case insensitive.
count=0 means make all possible replacements.
count=n (n > 0) means make the first n possible replacements.
"""
import re
if case == 0:
p = re.compile(regex, re.IGNORECASE)
else:
p = re.compile(regex)
return p.sub(repl, astr, count)
In shell:
>>> astr = "Now is the time 4 all good men."
>>> regex = r"[ohen0-9]"
>>> repl = "X"
>>> replace2(astr, regex, repl, case=0, count=0)
'XXw is tXX timX X all gXXd mXX.'
>>> replace2(astr, regex, repl)
'XXw is tXX timX X all gXXd mXX.'
>>> replace2(astr, regex, repl, case=1)
'NXw is tXX timX X all gXXd mXX.'
>>> replace2(astr, regex, repl, count=4)
'XXw is tXX time 4 all good men.'
>>>
(I've also pasted the above at < http://py77.python.pastebin.com/f18e323db>)
There's a string method, replace(); I can't use that name for my function, so unimaginatively I've gone with replace2(). Got a better name?
But more importantly, how can I improve replace()?
Thanks,
Dick Moores
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor