DeprecationWarning: invalid escape sequence"?-6ren"> DeprecationWarning: invalid escape sequence"?-我在 Python 中收到很多这样的警告: DeprecationWarning: invalid escape sequence \A orcid_regex = '\A[0-9]{4}-[0--6ren">
gpt4 book ai didi

python - 如何修复Python中的 " DeprecationWarning: invalid escape sequence"?

转载 作者:行者123 更新时间:2023-12-03 02:56:09 30 4
gpt4 key购买 nike

我在 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 \(

它们是什么意思?我该如何修复它们?

最佳答案

\ 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"""...""")。

关于python - 如何修复Python中的 "<string> DeprecationWarning: invalid escape sequence"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335970/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com