Python re.sub with non-raw replacement "\1!" inserts chr(1) instead of group 1; use r"\1!"
@aiden-f-dsouza▲ 7 net votes
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.