Pep8对 Python 中的正则表达式字符串的警告,Eclipse

为什么 pep8在代码的下一个字符串上抱怨?

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

我收到的警告是:

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

你能解释一下这条信息的意思吗?为了传递警告 W1401,我需要在代码中做什么更改?

代码通过测试并按预期运行。此外,\d{3}是一个有效的正则表达式。

53464 次浏览

"\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}")

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.