How to comment out a block of code in Python [dupl

2019-01-12 14:01发布

This question already has an answer here:

Is there a mechanism to comment out large blocks of Python code?

Right now, the only ways I can see of commenting out code are to either start every line with a #, or to enclose the code in triple quotes: """.

The problem with these is that inserting # before every line is cumbersome and """ makes the string I want to use as a comment show up in generated documentation.

After reading all comments, the answer seems to be "No".

19条回答
够拽才男人
2楼-- · 2019-01-12 14:08

Python does not have such a mechanism. Prepend a # to each line to block comment. For more information see PEP 8. Most Python IDEs support a mechanism to do the block-commenting-with-pound-signs automatically for you. For example, in IDLE on my machine, it's Alt+3 and Alt+4.

Don't use triple-quotes; as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.

查看更多
唯我独甜
3楼-- · 2019-01-12 14:10

In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.

查看更多
Juvenile、少年°
4楼-- · 2019-01-12 14:11

At least in VIM you can select the first column of text you want to insert using Block Visual mode (CTRL+V in non-windows VIMs) and then prepend a # before each line using this sequence:

I#<esc>

In Block Visual mode I moves to insert mode with the cursor before the block on its first line. The inserted text is copied before each line in the block.

查看更多
Juvenile、少年°
5楼-- · 2019-01-12 14:17

The only cure I know for this is a good editor. Sorry.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-01-12 14:17

The only mechanism to comment out Python code (understood as code ignored by the interpreter) is the #.

As you say, you can also use string literals, that are not ignored by the interpreter, but can be completely irrelevant for the program execution.

查看更多
我只想做你的唯一
7楼-- · 2019-01-12 14:20

In Visual Studio using the Python Tools for Visual Studio, blocks can be commented out by Ctrl+K, Ctrl+C and uncommented by Ctrl+K, Ctrl+U.

查看更多
登录 后发表回答