Sea*_*ond 21 python python-3.x python-3.6
我在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 \(
Run Code Online (Sandbox Code Playgroud)
他们的意思是什么?我该如何解决它们?
Sea*_*ond 24
例如,如果要在字符串中放置制表符,则可以执行以下操作:
>>> print("foo \t bar")
foo bar
Run Code Online (Sandbox Code Playgroud)
如果要将\字符串放在字符串中,则必须使用\\:
>>> print("foo \\ bar")
foo \ bar
Run Code Online (Sandbox Code Playgroud)
或者使用"原始字符串":
>>> print(r"foo \ bar")
foo \ bar
Run Code Online (Sandbox Code Playgroud)
你不能随意在字符串文字中添加反斜杠.如果没有其中一个有效的转义序列,则反斜杠无效,而较新版本的Python会打印弃用警告.例如\A,不是转义序列:
$ python3.6 -Wd -c '"\A"'
<string>:1: DeprecationWarning: invalid escape sequence \A
Run Code Online (Sandbox Code Playgroud)
如果你的反斜杠序列意外地匹配了Python的一个转义序列,但是你没有意思到它,那就更糟了.
所以你应该总是使用原始字符串或\\.
重要的是要记住,即使该字符串旨在用作正则表达式,字符串文字仍然是字符串文字.Python的正则表达式语法支持许多以特殊序列开头的序列\.例如,\A匹配字符串的开头.但是\A在Python字符串文字中无效!这是无效的:
my_regex = "\Afoo"
Run Code Online (Sandbox Code Playgroud)
相反,你应该这样做:
my_regex = r"\Afoo"
Run Code Online (Sandbox Code Playgroud)
Docstrings是另一个值得记住的:docstrings也是字符串文字,无效\序列在文档字符串中也是无效的!r"""..."""如果文档字符串包含原始字符串(),则使用原始字符串()\.
| 归档时间: |
|
| 查看次数: |
7853 次 |
| 最近记录: |