Python 3.7 with regular expressions: Why can I no longer substitute with a string containing a backslash (\)?


R. Hahnemann

For my problem, I've got a very simple example:

import re
my_string = re.sub(r"Hello", r"\Greetings", "Hello Folks!")

The above, in Python 3.6, will print \Greetings Folks! to the standard output. Let's try this again in Python 3.7.0 or 3.7.4 (the versions which I was able to test). What happens? We receive an error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.7/", line 192, in sub
return _compile(pattern, flags).sub(repl, string, count)
File "/usr/lib/python3.7/", line 309, in _subx
template = _compile_repl(template, pattern)
File "/usr/lib/python3.7/", line 300, in _compile_repl
return sre_parse.parse_template(repl, pattern)
File "/usr/lib/python3.7/", line 1024, in parse_template
raise s.error('bad escape %s' % this, len(this))
re.error: bad escape \G at position 0

Why is this? Is there a change in Python 3.7 which I've missed? What's the proper way around this problem? know a way around this problem (apart from using Python 3.6)?

Continue reading...