为什么Python允许三引号作为多行注释和字符串的文字形式

问题描述 投票:1回答:1

我是python的新手,这个问题可能听起来很傻,但我想弄清楚。在学习的过程中,我发现python允许三引号(""")作为多行注释和字符串文字。那么python是如何知道它是作为注释还是字符串文字的呢。

"""This
is treated
as comment
and ignored"""

a = """It is
treated as
string literal"""
print(a)

输出:-

It is
treated as
string literal
python syntax comments
1个回答
1
投票

本质上,如果三引号没有分配给一个变量或一个文档字符串,python会忽略它。例如

""""This is a module-level docstring""""


def randomFunction():
   """This will be treated as a docstring,
   so if you were to run help(randomFunction) it 
   will display whatever is in here"""


   a = """This is actually assigned to a variable,
   and thus python will interpret it as such"""

   """This by itself is just an unassigned string variable """

同样的情况也发生在字符串上,字符串在两个引号里面。

© www.soinside.com 2019 - 2024. All rights reserved.