Serhiy Storchaka <storchaka+cpyt...@gmail.com> added the comment:
If you want to replace %d with literal \d, you need to repeat the backslash 4 times: pattern = re.sub('%d', '\\\\d+', pattern) or use a raw string literal and repeat the backslash 2 times: pattern = re.sub('%d', r'\\d+', pattern) Since the backslash has a special meaning in the replacement pattern, it needs to be escaped with a backslash, i.e. duplicated. But since it has a special meaning in Python string literals, every of these backslashes needs to be escaped with a backslash in a non-raw string literal, i.e. repeated 4 times. Python 3.6 is more lenient. It keeps a backslash if it is followed by a character which doesn't compound a known escape sequences in a replacement string. But it emits a deprecation warning, which you can see when run Python with corresponding -W option. $ python3.6 -Wa -c 'import re; print(re.sub("%d", "\d+", "DBMS_NAME: string(%d) %s"))' <string>:1: DeprecationWarning: invalid escape sequence \d /usr/lib/python3.6/re.py:191: DeprecationWarning: bad escape \d return _compile(pattern, flags).sub(repl, string, count) DBMS_NAME: string(\d+) %s $ python3.6 -Wa -c 'import re; print(re.sub("%d", "\\d+", "DBMS_NAME: string(%d) %s"))' /usr/lib/python3.6/re.py:191: DeprecationWarning: bad escape \d return _compile(pattern, flags).sub(repl, string, count) DBMS_NAME: string(\d+) %s $ python3.6 -Wa -c 'import re; print(re.sub("%d", "\\\d+", "DBMS_NAME: string(%d) %s"))' <string>:1: DeprecationWarning: invalid escape sequence \d DBMS_NAME: string(\d+) %s $ python3.6 -Wa -c 'import re; print(re.sub("%d", "\\\\d+", "DBMS_NAME: string(%d) %s"))' DBMS_NAME: string(\d+) %s Here "invalid escape sequence \d" is generated by the Python parser, "bad escape \d" is generated by the RE engine. ---------- nosy: +serhiy.storchaka resolution: -> not a bug stage: -> resolved status: open -> closed _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue34304> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com