为什么 python 允许三引号作为多行注释和字符串文字

why python allows triple quotes both as multi-line comment as well as string literal

我是 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 将忽略它。例如

""""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 """

两个引号内的字符串也是如此。