[Tutor] use of variables in re.sub

Oscar Benjamin oscar.j.benjamin at gmail.com
Fri Feb 15 01:29:38 CET 2013


On 14 February 2013 12:57, Eva Bofias <eva.bofias at gmail.com> wrote:
> Helo,

Hi,

> I need to do a substitution in a regular expression that depends on a
> variable. To simplify I want to be able to do this substitution:
>
> text2='XX. AA YY. DD'
> re.sub(ur"\. (AA|BB|ÇÇ","(.) \g<1>",text2)

There is a missing bracket in that expression. did you mean ur"\. (AA|BB|ÇÇ)"?

> this would give as a result:
> 'XX(.) AA YY. DD'
> Which is exactly what I want.
>
> But when I try to substitute AA|BB|CC for a variable I do not know how to
> make it work.

How about this?

>>> import re
>>> text2='XX. AA YY. DD'
>>> re.sub(ur"\. (AA|BB|ÇÇ)",r"(.) \g<1>",text2)  # ¡Note the r"" raw string!
'XX(.) AA YY. DD'


Or have I misunderstood?


Oscar


More information about the Tutor mailing list