Python re.sub replacement string raises "re.error: bad escape \d at position 0"
@shreyanshsaurabh01▲ -1 net votes
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.