Goofy re.sub behavior

B

Blair Fraser

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.

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.
 
G

Gary Herron

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.


do it f}!


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.


This is exactly the behavior specified in the re documentation:

sub(pattern, repl, string[, count])
Return the string obtained by replacing the leftmost
non-overlapping occurrences of pattern in string by the
replacement repl. If the pattern isn't found, string is returned
unchanged. repl can be a string or a function; if it 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. For example:

Try doubling up your backslashes. Alternately, if you don't need any
of the regular expression machinery, perhaps you could just use the
'sub' method of string class.

Gary Herron
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top