Replacing tabs with spaces in Python code

There are various reasons why it’s a good idea to stick with using four spaces instead of a tab character in Python code. I’m not going to rehash that particular flamewar inducing arguement here.

I like to use spaces to indent my Python code (and have set up Vim accordingly), but occasionally I have some old code (or other peoples code) which uses tab characters. Python tends to complain about files that mix up both tabs and spaces for indenting, so I need to make these files uniform.

Here’s a really simple way to replace tabs with four spaces using sed on the commandline:

sed 's/\\t/    /g' >

This is really simple sed-101, but I’ve put it here just to remind myself it works.


UPDATE: I’ve discovered an easier way !

Simply using the vim command,


I can replace all tabs in the current text to match my vim tab settings, which in effect turns each tab to four spaces.

Some search and replace like:

:%s/\\t/    /g

would have also done it, but then you have to explicitly specify the four spaces.

For the record, here is my current ~/.vimrc file:

set guifont=LiberationMono
:colorscheme murphyset expandtab
set tabstop=4
set shiftwidth=4

In addition to the tabs-to-spaces stuff, there is also some font and color scheme stuff in there, since I prefer green text on a black background.

One thought on “Replacing tabs with spaces in Python code

Leave a Reply

Your email address will not be published. Required fields are marked *