[Tutor] substituting with a group

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Mon, 8 Jul 2002 01:04:37 -0700 (PDT)


On Mon, 8 Jul 2002, Paul Tremblay wrote:

> Given the following line:
>
> {the quick {brown fox"
>
> I want to produce the following line:
>
> <the> quick <brown> fox
>
> I know that in perl, you use an expression like this:
>
> $string =~ s/\{(\w+)/<$1>/g;
>
> In other words, I want to substitute using the group generated
> from the search. How do you do this in python?

Hi Paul,

Instead of using "$1", Python's regular expression engine uses '\1'
instead.  So you can do something like:

###
>>> re.sub(r'(\w+) (\w+)', r'\2 \1', 'hello world this is a test')
'world hello is this test a'
###


Hope this helps!