简体   繁体   English

Python IndentationError:意外的缩进

[英]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 = 'http://www.wpemergencia.omie.es//datosPub/marginalpdbc/marginalpdbc_' + fecha + '.1'
    # Descargamos fichero
    response = urllib2.urlopen(url)
    # Abrimos fichero
    output = open(fname,'wb')
    # Escribimos fichero
    output.write(response.read())
    # Cerramos y guardamos fichero
    output.close()
    # fecha++
    d += delta

Run your program with 运行你的程序

python -t script.py

This will warn you if you have mixed tabs and spaces. 如果您有混合标签和空格,这将警告您。

On *nix systems, you can see where the tabs are by running 在* nix系统上,您可以通过运行查看选项卡的位置

cat -A script.py

and you can automatically convert tabs to 4 spaces with the command 并且您可以使用该命令自动将制表符转换为4个空格

expand -t 4 script.py > fixed_script.py

PS. PS。 Be sure to use a programming editor (eg emacs, vim), not a word processor, when programming. 编程时一定要使用编程编辑器(例如emacs,vim),而不是文字处理器。 You won't get this problem with a programming editor. 使用编程编辑器不会出现此问题。

PPS. PPS。 For emacs users, Mx whitespace-mode will show the same info as cat -A from within an emacs buffer! 对于emacs用户, Mx whitespace-mode将在emacs缓冲区中显示与cat -A相同的信息!

在notepad ++中查找所有选项卡并替换为4个空格。它工作正常。

检查是否混合了制表符和空格,这是缩进错误的常见原因。

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! 另请注意,您的实际问题可能在于此块之前的行,并且python会在此处抛出错误,因为前导无效缩进与以下标识不匹配!

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. 现在执行此代码,在sublime中使用ctrl + b,现在它将在控制台中打印缩进代码。 that's it 而已

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM