Convert tabs to spaces for Python code

I used to develop Python code with tabs for indentation.  I don’t want to get into the religious debate of tabs vs spaces, but the Python community goes with 4 spaces for indentation.  So to allow ease of importing others code and contributing to other projects I decided to switch to spaces.

Updating Code

Update all your files is easy with find and sed:

find -name "*.py" | xargs -n 1 sed -i 's/\t/    /g'

Note: I would strongly suggest you do this on files that are under version control in case something goes wrong.

Vim Settings

Want to use spaces for Python code, but everything else using spaces?  Then add the following to your .vimrc:

au FileType python set expandtab
au FileType python setl shiftwidth=4 tabstop=4

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.