[Tutor] Multiple search and replace?

Peter Otten __peter__ at web.de
Thu May 2 19:42:30 CEST 2013


Andy McKenzie wrote:

> Hey folks,
> 
>   I'm trying to figure out how to do something, and it feels like it
>   should
> be possible, but I can't figure out how.  What I want is to define four
> expressions, like so:
> 
> (\sNorth\s|\sN\s)(\sSouth\s|\sS\s)(\sEast\s|\sE\s)(\sWest\s|\sW\s)
> 
> And then run a replace such that the groups are replaced, in order, with
> "N ", "S ", "E ", or "W " (capital letters, no spaces before).
> 
> It's easy enough to use re.sub to replace ONE of those, and I could just
> do
> that four times, but is there a way to do all at once?  It looks from some
> things I've seen like it should be, but I can't figure out how.

re.sub() accepts a function where you can do anything you like:

>>> r = re.compile(r"\b(red|yellow|blue)\b")
>>> def sub(match):
...     s = match.group(1)
...     return {"red": "pink", "yellow": "monsters"}.get(s, "starts to cry")
... 
>>> r.sub(sub, "Who's afraid of red yellow and blue?")
"Who's afraid of pink monsters and starts to cry?"

>>> re.compile(r"\b(north|south|east|west)\b").sub(lambda m: m.group(1)[:1],
... "north by northwest, south of southpark")
'n by northwest, s of southpark'




More information about the Tutor mailing list