怎么修 ” DeprecationWarning:“无效的转义序列”在Python中?
我在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 \(
他们的意思是什么?我该如何解决?
-
例如,如果要在字符串中放入制表符,则可以执行以下操作:
>>> print("foo \t bar") foo bar
如果要将文字
\
放在字符串中,则必须使用\\
:>>> print("foo \\ bar") foo \ bar
或使用“原始字符串”:
>>> print(r"foo \ bar") foo \ bar
您不能只在需要时就在字符串文字中添加反斜杠。如果反斜杠后面没有有效的转义序列之一,则该反斜杠无效,并且新版本的Python会显示弃用警告。例如
\A
不是转义序列:$ python3.6 -Wd -c '"\A"' <string>:1: DeprecationWarning: invalid escape sequence \A
如果您的反斜杠序列确实意外地与Python的转义序列之一匹配,但您不是故意这么做的,那就更糟了。
因此,您应始终使用原始字符串或
\\
。重要的是要记住,即使字符串打算用作正则表达式,字符串文字仍然是字符串文字。Python的正则表达式语法支持以开头的许多特殊序列
\
。例如,\A
匹配字符串的开头。但是\A
在Python字符串文字中无效!这是无效的:my_regex = "\Afoo"
相反,您应该这样做:
my_regex = r"\Afoo"
文档字符串是另一个要记住的内容:文档字符串也是字符串文字,并且无效
\
序列在文档字符串中也是无效的!r"""..."""
如果原始字串()包含,请使用原始字串()\
。