如何做多行注释?大多数语言都有块注释符号,比如:

/*

*/

当前回答

多行注释实际上在Python中并不存在。下面的示例包含一个未赋值的字符串,Python将验证该字符串是否存在语法错误。

一些文本编辑器,如notepad++,为我们提供了注释掉一段书面代码或单词的快捷方式。

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

此外,Ctrl + K是notepad++中阻止注释的快捷键。它在选定的每一行前面添加一个#。Ctrl + Shift + K表示取消注释。

其他回答

不幸的是,字符串化不能总是用于注释!因此,坚持在每行前加上#的标准更安全。

这里有一个例子:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

在其他答案中,我发现最简单的方法是使用IDE注释函数,该函数使用Python注释支持#。

我正在使用Anaconda Spyder,它有:

Ctrl + 1 -注释/取消注释 Ctrl + 4 -注释代码块 Ctrl + 5 -取消注释代码块

它可以用#注释/取消注释一行/多行代码。

我觉得这是最简单的。

例如,一个块注释:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

多行注释实际上在Python中并不存在。下面的示例包含一个未赋值的字符串,Python将验证该字符串是否存在语法错误。

一些文本编辑器,如notepad++,为我们提供了注释掉一段书面代码或单词的快捷方式。

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

此外,Ctrl + K是notepad++中阻止注释的快捷键。它在选定的每一行前面添加一个#。Ctrl + Shift + K表示取消注释。

我建议不要在多行注释中使用“”!

这里有一个简单的例子来强调可能被认为是意外的行为:

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

选择要注释的行,然后使用Ctrl + ?在Sublime文本编辑器中注释或取消注释Python代码。

对于单行,可以使用Shift + #。