在Python中,我收到了很多类似这样的警告:
DeprecationWarning: invalid escape sequence \A
orcid_regex = '\A[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{3}[0-9X]\Z'
DeprecationWarning: invalid escape sequence \/
AUTH_TOKEN_PATH_PATTERN = '^\/api\/groups'
DeprecationWarning: invalid escape sequence \
"""
DeprecationWarning: invalid escape sequence \.
DOI_PATTERN = re.compile('(https?://(dx\.)?doi\.org/)?10\.[0-9]{4,}[.0-9]*/.*')
<unknown>:20: DeprecationWarning: invalid escape sequence \(
<unknown>:21: DeprecationWarning: invalid escape sequence \(
它们是什么意思?我怎么才能修复它们呢?
发布于 2018-09-15 00:30:53
\
is the escape character in Python string literals。
例如,如果你想在字符串中放一个制表符,你可以这样做:
>>> print("foo \t bar")
foo bar
如果要将文字\
放入字符串中,则必须使用\\
>>> print("foo \\ bar")
foo \ bar
或者使用“原始字符串”:
>>> print(r"foo \ bar")
foo \ bar
你不能在你想要的时候在字符串中放反斜杠。如果反斜杠后面没有一个有效的转义序列和newer versions of Python print a deprecation warning,则该反斜杠无效。例如,\A
不是转义序列:
$ python3.6 -Wd -c '"\A"'
<string>:1: DeprecationWarning: invalid escape sequence \A
如果您的反斜杠序列确实意外地匹配了Python的转义序列之一,但您并不是故意的,那就更糟了。
因此,您应该始终使用原始字符串或\\
。
重要的是要记住,字符串文字仍然是字符串文字,即使该字符串打算用作正则表达式。Python's regular expression syntax支持许多以\
开头的特殊序列。例如,\A
匹配字符串的开头。但是\A
在Python字符串文字中无效!这无效:
my_regex = "\Afoo"
相反,您应该这样做:
my_regex = r"\Afoo"
文档字符串是另一个需要记住的:文档字符串也是字符串文字,无效的\
序列在文档字符串中也是无效的!如果文档字符串包含\
,请对其使用原始字符串(r"""..."""
)。
发布于 2020-05-11 09:51:19
当我将路径名称中的\更改为\时,解决了无效转义序列警告。请在下面找到附件中的截图以供参考。我在pycharm中得到了这个错误:
https://stackoverflow.com/questions/52335970
复制相似问题