How to comment out a block of Python code in Vim

You could add the following mapping to your .vimrc

vnoremap <silent> # :s/^/#/<cr>:noh<cr>
vnoremap <silent> -# :s/^#//<cr>:noh<cr>

Highlight your block with:

Shift+v

# to comment your lines from the first column.

-# to uncomment the same way.


Step 1: Go to the the first column of the first line you want to comment.

Initial State

Step 2: Press: Ctrl+v and select the lines you want to comment:

Select lines

Step 3: Shift-I#space (Enter Insert-at-left mode, type chars to insert. The selection will disappear, but all lines within it will be modified after Step 4.)

Comment

Step 4: Esc

<Esc>


Highlight your block with: ShiftV

Comment the selected block out with: :norm i# (lower case i)

To uncomment, highlight your block again, and uncomment with: :norm ^x

The :norm command performs an action for every selected line. Commenting will insert a # at the start of every line, and uncommenting will delete that #.


one way manually

:set number
:10,12s/^/#

Tags:

Python

Vim

Editor