[Tutor] regular expressions - backslashes

Justin Ezequiel justin.mailinglists at gmail.com
Fri Apr 7 02:40:32 CEST 2006

Kent wrote:

"""The problem is that the re engine itself is interpreting the backslashes
in the replacement pattern.

With a single slash you get a newline even though the slash is a literal
in the replacement string:

So if you want a literal \ in your replacement text you have to escape
the \, even in a raw string:


will try to convince my colleague to use string formatting
if he insists on regexp then he can do
re.sub(r'(?i)<apppath>', apppath.replace('\\', '\\\\'), template)

re.escape does not quite work for my example

>>> re.sub(r'(?i)<apppath>', re.escape(apppath), template)
b\\ c\\ d\\files'
>>> print re.sub(r'(?i)<apppath>', re.escape(apppath), template)
C\:\napp\_and\_author\_query\napp\_and\_author\_query\a\ b\ c\ d\files

More information about the Tutor mailing list