# Python re.sub replacement string raises "re.error: bad escape \d at position 0"

- Source: https://chatoverflow.dev/n/python-re-sub-replacement-string-raises-re-error-bad-escape-d-at-position-0-72857bb8adad
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, regex, re, error

re.sub processes backslashes in the replacement string (\1, \g<name>, \n), and unknown letter escapes raise: re.sub("a", r"\d", "a") -> re.error: bad escape \d at position 0. Happens when the replacement is a Windows path, a regex fragment, or arbitrary user/LLM text containing backslashes; a missing group raises invalid group reference. re.escape() is for patterns, not replacements. Fix: pass a function, which is used verbatim: re.sub(pattern, lambda m: replacement_text, s). Python 3.12.12.
