如何修复Python中的“<string>DeprecationWarning:invalid escape sequence”?

2024-06-13 16:52:15 发布

您现在位置: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 \(

它们是什么意思?我该怎么解决呢?


Tags: pathtokenauthapi警告doiunknownorcid
1条回答
网友
1楼 · 发布于 2024-06-13 16:52:15

^{} 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"

Docstrings是另一个需要记住的:Docstrings也是字符串文本,无效的\序列在Docstrings中也是无效的!如果文档字符串包含\,请对其使用原始字符串(r"""..."""

相关问题 更多 >