Goofy re.sub behavior

Blair Fraser crail_hudson at yahoo.com
Fri Oct 31 16:24:30 EST 2003


This seems incredibly bizzare.  I'm trying to sub in a string with a
backslash using re.sub.  If that string has a \b in it I can't stop it
from being interpreted as a backspace, even though the string is a raw
string and prints correctly.

>>> sub_in_x = r'{\bf}'   # This one won't work
>>> sub_in_y = r'{\if}'   # This one will work, but I don't want a \if
>>> print sub_in_x        # Prints with \b as a slash and a b
{\bf}
>>> print sub_in_y        # Also prints correctly
{\if}
>>> print re.sub(r'here', sub_in_x, 'do it here!')  # ?!?
do it f}!                                          
>>> print re.sub(r'here', sub_in_y, 'do it here!')  # \i works fine
do it {\if}!                                       
>>>

In the first case the \b is being re-interpreted as a backspace and
deleting the opening curly bracket.  However it initially prints as
the string I want as a substitution.




More information about the Python-list mailing list