【问题标题】:why python allows triple quotes both as multi-line comment as well as string literal为什么 python 允许三引号作为多行注释和字符串文字
【发布时间】:2020-09-23 01:47:05
【问题描述】:

我是 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】:

本质上,如果三引号未分配给变量或文档字符串,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 """

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

【讨论】:

  • 这对所有字符串文字都是正确的,不是吗?三引号只是给你多行字符串。
  • 是的,所有三引号都是多行字符串,但是 python 解释的方式取决于它的上下文。如上所述。
  • 我的意思是,您可以将第一个示例替换为"This by,itself will be ignored"['this', 'will', 'be', 'ignored']。三重引号没有什么特别之处,可以忽略不计。如果您不对其进行任何操作,随机表达式将被评估并丢弃。
  • 是的,我同意。因此,对他的问题的评论引用了它实际上不是评论,而是运行代码但没有做任何事情。
  • @MarkMeyer 感谢您的评论使其更加清晰。实际上,在这个网站上提到使用“””作为多线 cmets 的替代品,所以很困惑。programiz.com/python-programming/statement-indentation-comments
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-07
  • 2011-01-31
  • 2015-01-29
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多