注释与python中的字符串相比较

时间:2013-06-21 11:25:05

标签: python

我刚认识python 正如我所知,在python中,多行评论是这样的

"""
this is a comments
"""

但请考虑此代码

somevariable="""this is a variable"""
print somevariable

它打印 这是一个变量
python中的注释和字符串是相同的还是它们不同?

8 个答案:

答案 0 :(得分:5)

第一个不是评论,它是一个字符串。但是因为你不是做任何字符串(打印它,将它分配给变量等),所有解释器都会说“Yup,这是一个字符串好吧!”并完全忽略它。有效地使它与注释相同,因为它是一组被解释器忽略的任意文本。

答案 1 :(得分:4)

Python中没有多行注释。他们都只是字符串。前者通常用作docstring,并与函数/ class / module关联,而另一个则分配给变量。

答案 2 :(得分:2)

是的,它们是相同的

它被称为docstring 您可以在此处找到有关此类型字符串的更多信息: http://www.pythonforbeginners.com/basics/python-docstrings/

答案 3 :(得分:2)

  

是python中的注释和字符串相同吗?

严格来说,他们相同。但在你的问题中,你所谓的“评论”实际上是一个字符串。评论是#字符后出现在同一行中的所有内容。

a.py:

"""
comment1
"""
# comment2

现在:

% strings a.pyc | grep comment
comment1

如您所见,comment2不是已编译字节代码的一部分,而comment1是 - 因为它不是注释,而是字符串。

正如其他人指出的那样,该字符串被视为docstringdocstring通常用于记录您的代码,而评论则用于评论,并且不包含在文档中。

答案 4 :(得分:1)

是的,它们是一样的。包含注释字符串作为函数或类的第一个语句是一种约定。

请参阅PEP 257 -- Docstring Conventions

答案 5 :(得分:1)

第一个片段不是评论。这是一个字符串。 Python中的注释以#字符为前缀。

答案 6 :(得分:1)

>>> somevariable="""
... this is not a comment
... """
>>> print(somevariable)

this is not a comment

答案 7 :(得分:1)

混乱来自于文档字符串。

这实际上不是评论,而是制作包含多行的字符串的方法:

>>> """This is a string
... with line breaks"""
'This is a string\nwith line breaks'

在类和函数中使用相同的表示法来记录它们:

>>> def my_function():
...     """This function does stupid things."""
...     return 1/0
...
>>> my_function.__doc__
'This function does stupid things.'
>>> my_function()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in my_function
ZeroDivisionError: division by zero

所以你的代码:

somevariable = """this is a variable"""

真的等于:

somevariable = "this is a variable"
相关问题