如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
当前回答
我建议不要在多行注释中使用“”!
这里有一个简单的例子来强调可能被认为是意外的行为:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
现在看一下输出:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
多行字符串不被视为注释,但它与'显然我也是一个字符串'连接起来,形成一个单一的字符串。
如果您想注释多行,请根据PEP 8指南执行:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
输出:
I am a string
clearly I am also a string
其他回答
Python确实有一个多行字符串/注释语法,在这种意义上,除非用作文档字符串,多行字符串不会生成字节码——就像#- prependedcomments一样。实际上,它的作用完全像注释。
另一方面,如果您说这种行为必须在官方文档中记录,才能成为真正的注释语法,那么是的,您说它不保证是语言规范的一部分是正确的。
在任何情况下,您的文本编辑器还应该能够轻松地注释掉所选区域(通过在每行前面单独放置#)。如果不是,切换到一个文本编辑器。
在没有特定文本编辑功能的情况下使用Python编程可能是一种痛苦的体验。找到正确的编辑器(并知道如何使用它)会对如何感知Python编程体验产生很大的影响。
文本编辑器不仅应该能够注释掉所选区域,还应该能够轻松地将代码块向左或向右移动,并且当您按下Enter时,它应该自动将光标置于当前缩进级别。代码折叠也很有用。
为了防止链接衰减,以下是Guido van Rossum的推文内容:
Python提示:你可以使用多行字符串作为多行注释。除非用作文档字符串,否则它们不会生成代码!: -)
我认为它没有,除了一个多行字符串没有被处理。然而,大多数(如果不是所有的话)Python ide都有一个短键来“注释掉”多行代码。
我建议不要在多行注释中使用“”!
这里有一个简单的例子来强调可能被认为是意外的行为:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
现在看一下输出:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
多行字符串不被视为注释,但它与'显然我也是一个字符串'连接起来,形成一个单一的字符串。
如果您想注释多行,请根据PEP 8指南执行:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
输出:
I am a string
clearly I am also a string
不幸的是,字符串化不能总是用于注释!因此,坚持在每行前加上#的标准更安全。
这里有一个例子:
test1 = [1, 2, 3, 4,] # test1 contains 4 integers
test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'
从公认的答案…
你可以使用三引号字符串。当它们不是文档字符串(类/函数/模块中的第一件事)时,它们将被忽略。
这是不正确的。与注释不同,三引号字符串仍然被解析,并且必须在语法上有效,无论它们出现在源代码中的哪个位置。
如果你试图运行这段代码…
def parse_token(token):
"""
This function parses a token.
TODO: write a decent docstring :-)
"""
if token == '\\and':
do_something()
elif token == '\\or':
do_something_else()
elif token == '\\xor':
'''
Note that we still need to provide support for the deprecated
token \xor. Hopefully we can drop support in libfoo 2.0.
'''
do_a_different_thing()
else:
raise ValueError
你会得到…
ValueError: invalid \x escape
...Python 2。x或…
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape
...Python 3.x。
做被解析器忽略的多行注释的唯一方法是…
elif token == '\\xor':
# Note that we still need to provide support for the deprecated
# token \xor. Hopefully we can drop support in libfoo 2.0.
do_a_different_thing()