How to comment 20 lines of Python code on vim?

How to comment 20 lines of code at a time from a python file in vi/vim.

What command can I use instead of using # or """ ??

5

4 Answers

In vi:

  • navigate to the line where you wish to start commenting out
  • enter command mode (Esc then :)
  • type .,+20s/^/#/ or .,+20s/^/"""/ and hit Enter

What I typically do is this:

  1. Leave editing mode Esc, may need to hit couple times

  2. Press Shift+v to enter "Visual" mode

  3. Highlight the desired lines via arrow keys, or use 3j to select 3 lines down or 3k 3 lines up

  4. Enter command mode via :, and when you see :'<,'> displayed type in s/^/#/, and then hit Enter

This is visual approach, sort of like using a mouse in GUI to highlight lines, except without a mouse in vim

If you are using a Python IDE (As PyCharm) you can select these lines and use Ctrl+/ (or the default "comment" shortcut) to comment them.

If you are using a common text editor either you have to comment line per line or use the multi-line string (triple quotes) as a multi-line comment.

3

Vim can comment and uncomment multiple lines at once for specific lines range. Kindly check below example. here we will comment and uncomment from line numbers 7 to 13. Open file in vim

#vim /etc/hosts

run below two commands one by one

:se nu
:7,13s/^/#

done. for uncomment, run below one command

:7,13s/^#//

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like