The Greatest Linux Blog on the Internets.

Ubuntu, I 'buntu, We all 'buntu, (but only if we want'u).

The Greatest Linux Blog on the Internets. header image 2

Replacing tabs with spaces in Python code

August 17th, 2007 · 1 Comment · Python

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' oldcode.py >newcode.py

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,

:retab

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.

Tags:

One Comment so far ↓

Leave a Comment