pep8 warning on regex string in Python, Eclipse

雨燕双飞 提交于 2021-02-04 09:23:29

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/19030952/pep8-warning-on-regex-string-in-python-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!