有没有办法在Python中创建多行注释?

问题:有没有办法在Python中创建多行注释?

我最近开始研究Python,但是找不到如何实现多行注释。大多数语言都有块注释符号,例如

/*

*/

我在Python中尝试过此方法,但它引发了错误,因此这可能不是正确的方法。Python实际上是否具有多行注释功能?

I have recently started studying Python, but I couldn’t find how to implement multi-line comments. Most languages have block comment symbols like

/*

*/

I tried this in Python, but it throws an error, so this probably is not the correct way. Does Python actually have a multiline comment feature?


回答 0

您可以使用三引号引起来的字符串。如果它们不是文档字符串(类/函数/模块中的第一件事),则将其忽略。

'''
This is a multiline
comment.
'''

(请确保'''适当缩进引线,以避免出现IndentationError。)

Guido van Rossum(Python的创建者)在推特上发了一条“专业提示”。

但是,Python的样式指南PEP8 倾向于使用连续的单行注释,这也是在许多项目中都可以找到的。文本编辑器通常具有快捷方式来轻松实现此目的。

You can use triple-quoted strings. When they’re not a docstring (the first thing in a class/function/module), they are ignored.

'''
This is a multiline
comment.
'''

(Make sure to indent the leading ''' appropriately to avoid an IndentationError.)

Guido van Rossum (creator of Python) tweeted this as a “pro tip”.

However, Python’s style guide, PEP8, favors using consecutive single-line comments, and this is also what you’ll find in many projects. Text editors usually have a shortcut to do this easily.


回答 1

从某种意义上说,Python确实具有多行字符串/注释语法,除非多行字符串不用作文档字符串,否则不会生成字节码 -就像- #前置注释一样。实际上,它的行为就像评论一样。

另一方面,如果您说必须在官方文档中记录此行为才是真正的注释语法,那么可以,您可以肯定地说这不是语言规范的一部分。

无论如何,您的文本编辑器还应该能够轻松注释掉所选区域(通过#在每个行的前面分别放置一个)。如果不是,请切换到可以的文本编辑器。

没有某些文本编辑功能的Python编程可能会很痛苦。找到合适的编辑器(并知道如何使用它)可以在如何理解Python编程经验方面产生很大的不同。

文本编辑器不仅能够注释掉选定的区域,还应该能够轻松地向左和向右移动代码块,并且当您按时它应该自动将光标置于当前的缩进级别Enter。代码折叠也很有用。


为了防止链路衰减,这是Guido van Rossum的推文的内容

@BSUCSClub Python提示:您可以将多行字符串用作多行注释。除非用作文档字符串,否则它们不会生成任何代码!:-)

Python does have a multiline string/comment syntax in the sense that unless used as docstrings, multiline strings generate no bytecode — just like #-prepended comments. In effect, it acts exactly like a comment.

On the other hand, if you say this behavior must be documented in the official documentation to be a true comment syntax, then yes, you would be right to say it is not guaranteed as part of the language specification.

In any case, your text editor should also be able to easily comment-out a selected region (by placing a # in front of each line individually). If not, switch to a text editor that does.

Programming in Python without certain text editing features can be a painful experience. Finding the right editor (and knowing how to use it) can make a big difference in how the Python programming experience is perceived.

Not only should the text editor be able to comment-out selected regions, it should also be able to shift blocks of code to the left and right easily, and it should automatically place the cursor at the current indentation level when you press Enter. Code folding can also be useful.


To protect against link decay, here is the content of Guido van Rossum’s tweet:

@BSUCSClub Python tip: You can use multi-line strings as multi-line comments. Unless used as docstrings, they generate no code! :-)


回答 2

从接受的答案…

您可以使用三引号引起来的字符串。如果它们不是文档字符串(类/函数/模块中的第一件事),则将其忽略。

这是不正确的。与注释不同,三引号字符串仍然会被解析,并且在语法上必须有效,无论它们在源代码中的位置如何。

如果您尝试运行此代码…

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

你会得到…

ValueError: invalid \x escape

…在Python 2.x上…

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

…在Python 3.x上。

进行解析器忽略的多行注释的唯一方法是…

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

From the accepted answer…

You can use triple-quoted strings. When they’re not a docstring (first thing in a class/function/module), they are ignored.

This is simply not true. Unlike comments, triple-quoted strings are still parsed and must be syntactically valid, regardless of where they appear in the source code.

If you try to run this code…

def parse_token(token):
    """
    This function parses a token.
    TODO: write a decent docstring :-)
    """

    if token == '\\and':
        do_something()

    elif token == '\\or':
        do_something_else()

    elif token == '\\xor':
        '''
        Note that we still need to provide support for the deprecated
        token \xor. Hopefully we can drop support in libfoo 2.0.
        '''
        do_a_different_thing()

    else:
        raise ValueError

You’ll get either…

ValueError: invalid \x escape

…on Python 2.x or…

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 79-80: truncated \xXX escape

…on Python 3.x.

The only way to do multi-line comments which are ignored by the parser is…

elif token == '\\xor':
    # Note that we still need to provide support for the deprecated
    # token \xor. Hopefully we can drop support in libfoo 2.0.
    do_a_different_thing()

回答 3

在Python 2.7中,多行注释为:

"""
This is a
multilline comment
"""

如果您在Class里,应该正确地选择它。

例如:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

In Python 2.7 the multiline comment is:

"""
This is a
multilline comment
"""

In case you are inside a class you should tab it properly.

For example:

class weather2():
   """
   def getStatus_code(self, url):
       world.url = url
       result = requests.get(url)
       return result.status_code
   """

回答 4

AFAIK,Python没有阻止注释。要注释单个行,可以使用该#字符。

如果使用的是Notepad ++则有一个用于块注释的快捷方式。我敢肯定,像gVimEmacs这样的人也有类似的功能。

AFAIK, Python doesn’t have block comments. For commenting individual lines, you can use the # character.

If you are using Notepad++, there is a shortcut for block commenting. I’m sure others like gVim and Emacs have similar features.


回答 5

我认为没有,除了未处理多行字符串。但是,大多数(如果不是全部)Python IDE都具有用于“注释”多行代码的快捷键。

I think it doesn’t, except that a multiline string isn’t processed. However, most, if not all Python IDEs have a shortkey for ‘commenting out’ multiple lines of code.


回答 6

如果您发表评论

"""
long comment here
"""

在脚本中间,Python / lint无法识别。折叠将被弄乱,因为以上注释不是标准建议的一部分。最好用

# Long comment
# here.

如果使用Vim,则可以使用commentary.vim之类的插件通过按来自动注释掉较长的注释行Vjgcc。在其中Vj选择两行代码,并将gcc其注释掉。

如果您不想使用上述插件,则可以使用搜索和替换类似

:.,.+1s/^/# /g

这会将当前和下一行的第一个字符替换为#

If you put a comment in

"""
long comment here
"""

in the middle of a script, Python/linters won’t recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It’s better to use

# Long comment
# here.

If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc. Where Vj selects two lines of code, and gcc comments them out.

If you don’t want to use plugins like the above you can use search and replace like

:.,.+1s/^/# /g

This will replace the first character on the current and next line with #.


回答 7

没有多行注释等功能。#是注释一行代码的唯一方法。你们中的许多人都回答”’评论”’作为他们的解决方案。

它似乎可行,但是'''在Python 内部,它使用常规字符串将封闭的行作为解释器不会忽略的注释之类的注释#

在此处查看官方文档

There is no such feature as a multi-line comment. # is the only way to comment a single line of code. Many of you answered ”’ a comment ”’ this as their solution.

It seems to work, but internally ''' in Python takes the lines enclosed as a regular strings which the interpreter does not ignores like comment using #.

Check the official documentation here


回答 8

不幸的是,字符串化不能总是用作注释!因此,更安全的做法是坚持在每行前面加一个#

这是一个例子:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

Unfortunately stringification can not always be used as commenting out! So it is safer to stick to the standard prepending each line with a #.

Here is an example:

test1 = [1, 2, 3, 4,]       # test1 contains 4 integers

test2 = [1, 2, '''3, 4,'''] # test2 contains 2 integers **and the string** '3, 4,'

回答 9

好了,您可以尝试一下(在运行引号时,第一个问题的输入应用引号'):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

包括在内的任何内容"""都会被评论。

如果您要查找单行注释,则为#

Well, you can try this (when running the quoted, the input to the first question should quoted with '):

"""
print("What's your name? ")
myName = input()
print("It's nice to meet you " + myName)
print("Number of characters is ")
print(len(myName))
age = input("What's your age? ")
print("You will be " + str(int(age)+1) + " next year.")

"""
a = input()
print(a)
print(a*5)

Whatever enclosed between """ will be commented.

If you are looking for single-line comments then it’s #.


回答 10

Python中的多行注释:

对我来说,“”和“”都有效。

例:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

例:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)

Multiline comment in Python:

For me, both ”’ and “”” worked.

Example:

a = 10
b = 20
c = a+b
'''
print ('hello')
'''
print ('Addition is: ', a+b)

Example:

a = 10
b = 20
c = a+b
"""
print('hello')
"""
print('Addition is: ', a+b)

回答 11

Python中的内联注释以井号字符开头。

hello = "Hello!" # This is an inline comment
print(hello)

你好!

请注意,字符串文字中的哈希字符只是哈希字符。

dial = "Dial #100 to make an emergency call."
print(dial)

拨打#100拨打紧急电话。

哈希字符也可以用于单行或多行注释。

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

你好

世界

用三重双引号将文本括起来以支持文档字符串。

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

你好约翰!

将文本用三重单引号引起来以用于块注释。

'''
I don't care the parameters and
docstrings here.
'''

The inline comments in Python starts with a hash character.

hello = "Hello!" # This is an inline comment
print(hello)

Hello!

Note that a hash character within a string literal is just a hash character.

dial = "Dial #100 to make an emergency call."
print(dial)

Dial #100 to make an emergency call.

A hash character can also be used for single or multiple lines comments.

hello = "Hello"
world = "World"
# First print hello
# And print world
print(hello)
print(world)

Hello

World

Enclose the text with triple double quotes to support docstring.

def say_hello(name):
    """
    This is docstring comment and
    it's support multi line.
    :param name it's your name
    :type name str
    """
    return "Hello " + name + '!'


print(say_hello("John"))

Hello John!

Enclose the text with triple single quotes for block comments.

'''
I don't care the parameters and
docstrings here.
'''

回答 12

在Python 2.7.13上:

单:

"A sample single line comment "

多行:

"""
A sample
multiline comment
on PyCharm
"""

On Python 2.7.13:

Single:

"A sample single line comment "

Multiline:

"""
A sample
multiline comment
on PyCharm
"""

回答 13

Visual Studio Code通用官方多行注释切换。

macOS:选择代码块,然后+/

Windows:选择代码块,然后Ctrl+/

Visual Studio Code universal official multi-line comment toggle.

macOS: Select code-block and then +/

Windows: Select code-block and then Ctrl+/


回答 14

是的,可以同时使用以下两种:

'''
Comments
'''

"""
Comments
"""

但是,在IDE中运行时,您唯一需要记住的是,您必须“运行”整个文件才能被多行代码接受。逐行“运行”将无法正常工作,并会显示错误。

Yes, it is fine to use both:

'''
Comments
'''

and

"""
Comments
"""

But, the only thing you all need to remember while running in an IDE, is you have to ‘RUN’ the entire file to be accepted as multiple lines codes. Line by line ‘RUN’ won’t work properly and will show an error.


回答 15

要注释掉Python中的多行代码,只需#在每一行上使用单行注释:

# This is comment 1
# This is comment 2 
# This is comment 3

要在Python中编写“适当的”多行注释,是使用具有"""语法的多行字符串Python具有文档字符串(或文档字符串)功能。它为程序员提供了一种在每个Python模块,函数,类和方法中添加快速注释的简便方法。

'''
This is
multiline
comment
'''

另外,请注意,您可以通过这样的类对象访问docstring

myobj.__doc__

For commenting out multiple lines of code in Python is to simply use a # single-line comment on every line:

# This is comment 1
# This is comment 2 
# This is comment 3

For writing “proper” multi-line comments in Python is to use multi-line strings with the """ syntax Python has the documentation strings (or docstrings) feature. It gives programmers an easy way of adding quick notes with every Python module, function, class, and method.

'''
This is
multiline
comment
'''

Also, mention that you can access docstring by a class object like this

myobj.__doc__

回答 16

您可以使用以下内容。这称为DockString。

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__

You can use the following. This is called DockString.

def my_function(arg1):
    """
    Summary line.
    Extended description of function.
    Parameters:
    arg1 (int): Description of arg1
    Returns:
    int: Description of return value
    """
    return arg1

print my_function.__doc__

回答 17

我建议不要使用"""多行注释!

这是一个简单的示例,以突出显示可能被视为意外行为的内容:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

现在看一下输出:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

多行字符串不被视为注释,而是与之连接'clearly I'm also a string'形成一个字符串。

如果要注释多行,请按照PEP 8准则进行注释

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

输出:

I am a string
clearly I am also a string

I would advise against using """ for multi line comments!

Here is a simple example to highlight what might be considered an unexpected behavior:

print('{}\n{}'.format(
    'I am a string',
    """
    Some people consider me a
    multi-line comment, but
    """
    'clearly I am also a string'
    )
)

Now have a look at the output:

I am a string

    Some people consider me a
    multi-line comment, but
    clearly I am also a string

The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string' to form a single string.

If you want to comment multiple lines do so according to PEP 8 guidelines:

print('{}\n{}'.format(
    'I am a string',
    # Some people consider me a
    # multi-line comment, but
    'clearly I am also a string'
    )
)

Output:

I am a string
clearly I am also a string

回答 18

使用PyCharm IDE。

您可以使用Ctrl + /commentuncomment代码行。Ctrl + /注释或取消注释当前行或用单行注释注释掉若干行({# in Django templates, or # in Python scripts)Pressing Ctrl+Shift+/对于Django模板中选定的源代码块,该块用{% comment %} and {% endcomment %}标签包围。


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

选择所有行,然后按 Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

Using PyCharm IDE.

You can comment and uncomment lines of code using Ctrl+/. Ctrl+/ comments or uncomments the current line or several selected lines with single line comments ({# in Django templates, or # in Python scripts). Pressing Ctrl+Shift+/ for a selected block of source code in a Django template surrounds the block with {% comment %} and {% endcomment %} tags.


n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)

print("Loop ended.")

Select all lines then press Ctrl + /


# n = 5
# while n > 0:
#     n -= 1
#     if n == 2:
#         break
#     print(n)

# print("Loop ended.")

回答 19

多行注释实际上在Python中不存在。下面的示例包含一个未分配的字符串,该字符串已通过Python验证是否存在语法错误。

一些文本编辑器,例如Notepad ++,为我们提供了注释掉一段书面代码或单词的快捷方式。

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

另外,Ctrl+ K是Notepad ++中阻止评论的快捷方式。它#在所选内容的每行前面添加一个。Ctrl+ Shift+ K用于取消注释。

A multiline comment doesn’t actually exist in Python. The below example consists of an unassigned string, which is validated by Python for syntactical errors.

A few text editors, like Notepad++, provide us shortcuts to comment out a written piece of code or words.

def foo():
    "This is a doc string."
    # A single line comment
    """
       This
       is a multiline
       comment/String
    """
    """
    print "This is a sample foo function"
    print "This function has no arguments"
    """
    return True

Also, Ctrl + K is a shortcut in Notepad++ to block comment. It adds a # in front of every line under the selection. Ctrl + Shift + K is for block uncomment.


回答 20

在其他答案中,我发现最简单的方法是使用IDE注释函数,该函数使用的Python注释支持#

我正在使用Anaconda Spyder,它具有:

  • Ctrl+ 1-评论/取消评论
  • Ctrl+ 4-注释一段代码
  • Ctrl+ 5-取消注释代码块

它将使用注释/取消注释单行/多行代码#

我觉得最简单。

例如,一个块注释:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

Among other answers, I find the easiest way is to use the IDE comment functions which use the Python comment support of #.

I am using Anaconda Spyder and it has:

  • Ctrl + 1 – Comment/uncomment
  • Ctrl + 4 – Comment a block of code
  • Ctrl + 5 – Uncomment a block of code

It would comment/uncomment a single/multi line/s of code with #.

I find it the easiest.

For example, a block comment:

# =============================================================================
#     Sample Commented code in spyder
#  Hello, World!
# =============================================================================

回答 21

选择要注释的行,然后使用Ctrl+ ?注释或取消注释Sublime Text中的Python代码。编辑器中。

对于单行,可以使用Shift+ #

Select the lines that you want to comment and then use Ctrl + ? to comment or uncomment the Python code in the Sublime Text editor.

For single line you can use Shift + #.