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:20

Triple quotes are OK to me. You can use ''' foo ''' for docstrings and """ bar """ for comments or vice-versa to make the code more readable.

查看更多
虎瘦雄心在
3楼-- · 2019-01-12 14:22

Yes, there is (depending on your editor). In PyDev (and in Aptana Studio with PyDev):

  • Ctrl + 4 - comment selected block

  • Ctrl + 5 - uncomment selected block

查看更多
放荡不羁爱自由
4楼-- · 2019-01-12 14:23

The only way you can do this without triple quotes is to add an:

if False:

And then indent all your code. Note that the code will still need to have proper syntax.


Many Python IDEs can add # for you on each selected line, and remove them when un-commenting too. Likewise, if you use vi or Emacs you can create a macro to do this for you for a block of code.

查看更多
家丑人穷心不美
5楼-- · 2019-01-12 14:24

In JetBrains PyCharm on Mac use Command + / to comment/uncomment selected block of code. On Windows, use CTRL + /.

查看更多
一纸荒年 Trace。
6楼-- · 2019-01-12 14:26

Another editor-based solution: text "rectangles" in Emacs.

Highlight the code you want to comment out, then C-x-r-t #

To un-comment the code: highlight, then C-x-r-k

I use this all-day, every day. (Assigned to hot-keys, of course.)

This and powerful regex search/replace is the reason I tolerate Emacs's other "eccentricities".

查看更多
一纸荒年 Trace。
7楼-- · 2019-01-12 14:26

Use a nice editor like SciTe, select your code, press Ctrl + Q and done.

If you don't have an editor that supports block comments you can use a triple quoted string at the start and the end of your code block to 'effectively' comment it out. It is not the best practice though.

查看更多
登录 后发表回答