Python、Eclipse 中正则表达式字符串的 pep8 警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19030952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pep8 warning on regex string in Python, Eclipse
提问by alandarev
Why is pep8 complaining on the next string in the code?
为什么 pep8 抱怨代码中的下一个字符串?
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 W1401is passed?
你能解释一下消息的含义吗?我需要在代码中更改什么才能通过警告W1401?
The code passes the tests and runs as expected. Moreover \d{3}
is a valid regex.
代码通过了测试并按预期运行。此外\d{3}
是一个有效的正则表达式。
采纳答案by falsetru
"\d"
is same as "\\d"
because there's no escape sequence for d
. But it is not clear for the reader of the code.
"\d"
相同,"\\d"
因为 没有转义序列d
。但是代码的读者并不清楚。
But, consider \t
. "\t"
represent tab chracter, while r"\t"
represent literal \
and t
character.
但是,考虑\t
. "\t"
代表制表符,而r"\t"
代表文字\
和t
字符。
So use raw string when you mean literal \
and d
:
所以当你的意思是文字\
和时使用原始字符串d
:
re.compile(r"\d{3}")
or escape backslash explicitly:
或明确转义反斜杠:
re.compile("\d{3}")
回答by userA789
Python is unable to parse '\d'
as an escape sequence, that's why it produces a warning.
Python 无法解析'\d'
为转义序列,这就是它产生警告的原因。
After that it's passed down to regex parser literally, works fine as an E.S. for regex.
之后它从字面上传递给正则表达式解析器,作为正则表达式的 ES 工作正常。