Invalid Escape Sequence
ID |
python.invalid_escape_sequence |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Python |
Tags |
reliability, suspicious-construct |
Description
Reports string literals that contain a backslash followed by a character that is not a valid Python escape. CPython emits a DeprecationWarning (and Python 3.12+ a SyntaxWarning) for these. The implicit behaviour preserves the literal backslash and the following character, but the warning is a strong signal that the author meant a raw string.
path = "C:\Users\Admin" # FLAW — \U is invalid here
regex = "\d+" # FLAW — \d is not a string escape
path = r"C:\Users\Admin" # OK — raw string
regex = r"\d+" # OK
literal = "\\d+" # OK — escaped backslash
Rationale
The most common culprits are Windows paths and regular-expression patterns embedded in non-raw strings. Both compile, but the warning will fail tests on python -W error and become a SyntaxError on a future Python release.
Remediation
Use a raw string (r"…“) for paths and regex patterns, or double the backslash (”\\d+") when the literal really should contain a backslash.