The Greatest Linux Blog on the Internets. » read post

Replacing tabs with spaces in Python code

  • August 17th, 2007

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.


Related posts:

  • About
  • Making Linux systems that don’t suck
  • Ubuntu install on Asus P5K-E, Core2 Duo E6750
  • Trackback URL for this post: http://linuxblog.pansapiens.com/2007/08/17/replacing-tabs-with-spaces-in-python-code/trackback/

    One Person had this to say...

    scienceoss.com » Blog Archive » “unexpected indent” errors in Python Said...

    [...] are a couple more ways to convert tabs to [...]

    • March 20th, 2008 at 9:57 am

    Want your say?

    XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>