error in module re?

Tim Peters tim_one at email.msn.com
Mon Sep 13 20:55:15 EDT 1999


[Chris...]
>   Is this an implementation or documentation error?

Neither.

> >>> import re
> >>> re.sub('(a+)\s(b+)', '\2-\1', 'aaa bbb')
> '\002-\001'
> instead of
> 'bbb-aaa'
> The documentation says, that you can use backreferences in replacement
> string, but only \g<number> works.

Read the cautions about using regular strings with regexps, then get in the
habit of using r-strings.  This does what you want:

>>> re.sub(r'(a+)\s(b+)', r'\2-\1', 'aaa bbb')
'bbb-aaa'
>>>

assuming-anybody-could-want-that<wink>-ly y'rs  - tim






More information about the Python-list mailing list