Python IndentationError: unexpected indent


Here is my code … I am getting indentation error but i don’t know why it occurs.


# loop
while d <= end_date:
    # print d.strftime("%Y%m%d")
    fecha = d.strftime("%Y%m%d")
    # set url
    url = '' + fecha + '.1'
    # Descargamos fichero
    response = urllib2.urlopen(url)
    # Abrimos fichero
    output = open(fname,'wb')
    # Escribimos fichero
    # Cerramos y guardamos fichero
    # fecha++
    d += delta
Asked By: miguelfg



Check if you mixed tabs and spaces, that is a frequent source of indentation errors.

Answered By: ilstam

Run your program with

python -t

This will warn you if you have mixed tabs and spaces.

On *nix systems, you can see where the tabs are by running

cat -A

and you can automatically convert tabs to 4 spaces with the command

expand -t 4 >

PS. Be sure to use a programming editor (e.g. emacs, vim), not a word processor, when programming. You won’t get this problem with a programming editor.

PPS. For emacs users, M-x whitespace-mode will show the same info as cat -A from within an emacs buffer!

Answered By: unutbu

You can’t mix tab and spaces for identation. Best practice is to convert all tabs to spaces.

How to fix this? Well just delete all the spaces/tabs before each line and convert them uniformly either to tabs OR spaces, but don’t mix. Best solution: enable in your Editor the option to convert automagically any tabs to spaces.

Also be aware that your actual problem may lie in the lines before this block, and python throws the error here, because of a leading invalid indentation which doesn’t match the following identations!

Answered By: Don Question

find all tabs and replaced by 4 spaces in notepad ++ .It worked.

Answered By: user2287824

Simply copy your script and put under “”” your entire code “”” …

specify this line in a variable.. like,

a = """ your entire code """
print a.replace('    ','    ') # first 4 spaces tab second four space from space bar

print a.replace('here please press tab button it will insert some space"," here simply press space bar four times")
# here we replacing tab space by four char space as per pep 8 style guide..

now execute this code, in sublime using ctrl+b, now it will print indented code in console. that’s it

Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.