如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
如何做多行注释?大多数语言都有块注释符号,比如:
/*
*/
当前回答
选择要注释的行,然后使用Ctrl + ?在Sublime文本编辑器中注释或取消注释Python代码。
对于单行,可以使用Shift + #。
其他回答
在Python 2.7中,多行注释是:
"""
This is a
multilline comment
"""
如果你在一个类中,你应该正确地制表。
例如:
class weather2():
"""
def getStatus_code(self, url):
world.url = url
result = requests.get(url)
return result.status_code
"""
在其他答案中,我发现最简单的方法是使用IDE注释函数,该函数使用Python注释支持#。
我正在使用Anaconda Spyder,它有:
Ctrl + 1 -注释/取消注释 Ctrl + 4 -注释代码块 Ctrl + 5 -取消注释代码块
它可以用#注释/取消注释一行/多行代码。
我觉得这是最简单的。
例如,一个块注释:
# =============================================================================
# Sample Commented code in spyder
# Hello, World!
# =============================================================================
使用PyCharm IDE。
可以使用Ctrl+/对代码行进行注释和取消注释。 Ctrl+/用单行注释注释或取消注释当前行或几个选定的行(Django模板中的{#或Python脚本中的#)。 在Django模板中,对选中的源代码块按Ctrl+Shift+/,该代码块会被{% comment %}和{% endcomment %}标记包围。
n = 5
while n > 0:
n -= 1
if n == 2:
break
print(n)
print("Loop ended.")
选择所有行,然后按Ctrl + /
# n = 5
# while n > 0:
# n -= 1
# if n == 2:
# break
# print(n)
# print("Loop ended.")
你可以使用三引号字符串。当它们不是docstring(类/函数/模块中的第一件事)时,它们将被忽略。
'''
This is a multiline
comment.
'''
(确保适当缩进前导" '以避免出现IndentationError。)
Guido van Rossum (Python的创造者)在推特上发布了这条“专业提示”。
然而,Python的风格指南PEP8倾向于使用连续的单行注释,像这样:
# This is a multiline
# comment.
...这也是你在很多项目中会发现的。文本编辑器通常有一个快捷方式来轻松做到这一点。
我建议不要在多行注释中使用“”!
这里有一个简单的例子来强调可能被认为是意外的行为:
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