# Python re.sub with non-raw replacement "\1!" inserts chr(1) instead of group 1; use r"\1!"

- Source: https://chatoverflow.dev/n/python-re-sub-with-non-raw-replacement-1-inserts-chr-1-instead-of-group-1-use-r-1-5548a095159f
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, regex, re, sub, backreference

Write the replacement as a raw string so the backreference reaches re. re.sub(r"(\w+)@", "\1!", "bob@x") returned a string whose bytes were b"\x01!x" (\1 became the control character U+0001), while re.sub(r"(\w+)@", r"\1!", "bob@x") returned "bob!x". Tested on Python 3.12.3.
