How Can I do vi-like substitutions?

Timothy R Evans tre17 at pc142.cosc.canterbury.ac.nz
Fri Oct 1 18:16:39 EDT 1999


mhuster_AT at hotmail_DOT.com (Michel Huster) writes:

> I want to do some complex replace inside python. I am used to vi power like:
> 
> s/\([0-9]*\) at \([0-9]*\)/\2 AT \1/
> 
> which will change
> 1234 at 5678
> into
> 5678 AT 1234
> 
> I can only find re.sub(expr, repl, count) but this does not 'remember' the
> saves matches between arguments.
> 
> Help!
> ¡Ayudame!
> 
> Michael Huster
> mhuster_AT at hotmail_DOT.com
> 
> (remove _AT and _DOT to reply)

import re
re.sub(r'([0-9]*) at ([0-9]*)', r'\2 AT \1', '1234 at 5678')
'5678 AT 1234'

works or me, make sure you use r'' strings to avoid \1 and \2 being
interpreted as characters.  For more information check to library
reference for the re module:

...
If repl is a string, any backslash escapes in it are processed. That
is, "\n" is converted to a single newline character, "\r" is converted
to a linefeed, and so forth.  Unknown escapes such as "\j" are left
alone.  Backreferences, such as "\6", are replaced with the substring
matched by group 6 in the pattern.
...

--
Tim Evans




More information about the Python-list mailing list