由于注释而出错,这实际上不应该影响我在 python 中的程序

0 python

采取下面的代码:

"""
\u
"""
print("hello")
Run Code Online (Sandbox Code Playgroud)

该评论导致以下错误:

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 1-2: truncated \uXXXX escape
Run Code Online (Sandbox Code Playgroud)

如果我使用#评论而不是""" ... """我不会收到此错误:

我尝试在网上搜索,但我唯一发现的是它\U实际上有一个特殊的功能。然而,在本例中,它只是一条注释,那么为什么它会影响我的程序呢? 如果我写的话"""\t"""就不会有这样的错误。

tde*_*ney 5

这是一个三引号字符串,而不是注释。您可能在其他 .py 文件中看到过这些。模块顶部的未命名字符串成为其“文档字符串”,可以通过全局__doc__变量访问或在help(mymodule). 作为字符串,它遵循正常的 python 字符串文字规则,其中 a\u...开始 unicode 转义序列。

如果您想发表评论,请使用#

# \u
Run Code Online (Sandbox Code Playgroud)

但是,如果您想要一个文档字符串,您可以以“r”开头,使其成为原始字符串,其中反斜杠转义被忽略 - 或者完全避免字符串转义

r"""
\u
"""
Run Code Online (Sandbox Code Playgroud)

该字符串的目的是向其他人描述该模块,因此请使其简短且具有描述性。

mymodule.py:

r"""This program does the most
amazing things with \u
"""
Run Code Online (Sandbox Code Playgroud)

当在 shell 中运行时

>>> import mymodule
>>> help(mymodule)

Help on module mymodule:

NAME
    mymodule

DESCRIPTION
    This program does the most
    amazing things with \u

FILE
    /home/td/tmp/f/mymodule.py
Run Code Online (Sandbox Code Playgroud)