pep8 warning on regex string in Python, Eclipse

PythonStringEclipsePydevPep8

Python Problem Overview


Why is pep8 complaining on the next string in the code?

import re
re.compile("\d{3}")

The warning I receive:

ID:W1401  Anomalous backslash in string: '\d'. String constant might be missing an r prefix.

Can you explain what is the meaning of the message? What do I need to change in the code so that the warning W1401 is passed?

The code passes the tests and runs as expected. Moreover \d{3} is a valid regex.

Python Solutions


Solution 1 - Python

"\d" is same as "\\d" because there's no escape sequence for d. But it is not clear for the reader of the code.

But, consider \t. "\t" represent tab chracter, while r"\t" represent literal \ and t character.

So use raw string when you mean literal \ and d:

re.compile(r"\d{3}")

or escape backslash explicitly:

re.compile("\\d{3}")

Solution 2 - Python

Python is unable to parse '\d' as an escape sequence, that's why it produces a warning.

After that it's passed down to regex parser literally, works fine as an E.S. for regex.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalandarevView Question on Stackoverflow
Solution 1 - PythonfalsetruView Answer on Stackoverflow
Solution 2 - PythonuserA789View Answer on Stackoverflow