How to resolve the Python syntax warning "\d" is an invalid escape sequence
SyntaxWarning: "\d" is an invalid escape sequence
A few years ago, I created a bunch of Python scripts that run everyday. These scripts use regular expressions to parse out values, extract them and process them. This output is used to generate HTML files, Excel files and PDFs.
After upgrading Python to 3.13 and 3.14, these scripts started throwing up warnings of this type:
SyntaxWarning: "\d" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\d"? A raw string is also an option.
A simpler version of the code looks like this:
import re
pattern_ipv4 = '\d+\.\d+\.\d+\.\d+'
ip = '202.216.32.33'
regs = re.search(pattern_ipv4, ip)
if regs:
print(regs[0])
When you run it on the Python shell, you get the error:
:3: SyntaxWarning: "\d" is an invalid escape sequence. Such sequences will not work in the future. Did you mean "\\d"? A raw string is also an option.
Solution 💡
That warning shows up because these newer versions of Python interprets a backslash followed by a letter as an escape sequence, which may not be recognized.
In this case, Python 3.13 and 3.14 do not recognize \d as a number.
The solution for this is to use a raw string prefix with r'\d' instead of '\d'.
Change this line:
pattern_ipv4 = '\d+\.\d+\.\d+\.\d+'
to this:
pattern_ipv4 = r'\d+\.\d+\.\d+\.\d+'
So, the program changes to:
import re
pattern_ipv4 = r'\d+\.\d+\.\d+\.\d+'
ip = '202.216.32.33'
regs = re.search(pattern_ipv4, ip)
if regs:
print(regs[0])
Output:
202.216.32.33
Now, run the program and it will not show the syntax warning.
TL;DR Solution
Prefix the regex pattern that contains \d with raw prefix r'\d'.
Conclusion
Hope this solution worked for you. If it did or did not, please feel free to comment below. Thanks for reading.
Related Posts
If you have any questions, please contact me at arulbOsutkNiqlzziyties@gNqmaizl.bkcom. You can also post questions in our Facebook group. Thank you.