为什么多行注释中包含的值在python中有效

Pet*_*ete -1 python python-2.7

基本上我有一个print语句,其值包含在多行注释块中.我期待它是一个错误,但我发现它实际上打印了所附的文本.我很好奇它为什么这样做.

print '''Test String'''
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

Python没有多行注释语法.您对其中一个Python 字符串文字形式感到困惑.

'''....'''创建一个字符串,就像这样'...'.还有一个"""...."""表格.区别在于三重引用中允许换行而不需要转义:

multi_line_string = '''This is the first line.
But multiple lines are included.
And each newline is included in the value.
'''
Run Code Online (Sandbox Code Playgroud)

您可能认为这些是注释,因为Python开发人员在创建文档字符串时更喜欢这种形式.Python赋予字符串文字特殊含义,该字符串文字用作模块,类或函数中的第一个语句,将内容存储在object __doc__属性中.

你不具备使用三引号字符串的是,单引号工作太:

>>> def foo():
...     'The foo function'
...     return 'bar'
... 
>>> foo.__doc__
'The foo function'
Run Code Online (Sandbox Code Playgroud)

Python样式指南建议您使用双引号,总是使用双引号,如下所示:

def recommended():
    """This is a documentation string.

    It follows the style guide by using triple quotes.

    """
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅PEP 257:文档字符串约定.