Squezing in replacements into strings

Peter Bengtsson mail at peterbe.com
Mon Apr 25 08:42:38 EDT 2005


Peter Otten <__peter__ <at> web.de> writes:

> 
> > How can I do this this concatenation correctly?
> 
> I think sub() is more appropriate than finditer() for your problem, e. g.:
> 
> >>> def process(match):
> ...     return "_%s_" % match.group(1).title()
> ...
> >>> re.compile("(peter)", re.I).sub(process, "Peter Bengtsson PETER, or
> PeTeR")
> '_Peter_ Bengtsson _Peter_, or _Peter_'
> >>>

Ahaa! Great. I didn't realise that I can substitute with a callable that gets
the match object. Hadn't thought of it that way. 
Will try this now.




More information about the Python-list mailing list