Python IndentationError:意外缩进[重复]

问题描述 投票:0回答:5

这是我的代码...我收到缩进错误,但我不知道为什么会发生。

->

# 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
python indentation
5个回答
50
投票

运行你的程序

python -t script.py

如果您混合使用制表符和空格,这会警告您。

在 *nix 系统上,您可以通过运行来查看选项卡的位置

cat -A script.py

并且您可以使用命令自动将制表符转换为 4 个空格

expand -t 4 script.py > fixed_script.py

PS。编程时请务必使用编程编辑器(例如 emacs、vim),而不是文字处理器。使用编程编辑器不会遇到这个问题。

PPS。对于 emacs 用户,M-x

whitespace-mode
将在 emacs 缓冲区中显示与
cat -A
相同的信息!


9
投票

在记事本++中找到所有选项卡并替换为4个空格。它起作用了。


8
投票

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


3
投票

不能混合使用制表符和空格进行标识。最佳实践是将所有制表符转换为空格。

如何解决这个问题?好吧,只需删除每行之前的所有空格/制表符,并将它们统一转换为制表符或空格,但不要混合。最佳解决方案:在编辑器中启用将任何制表符自动转换为空格的选项。

还要注意,您的实际问题可能出在该块之前的行中,并且 python 会在此处抛出错误,因为前导无效缩进与以下标识不匹配!


0
投票

只需复制您的脚本并将整个代码放在“””下“””...

在变量中指定这一行..例如,

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..

现在执行这段代码,在 sublime 中使用 ctrl+b ,现在它将在控制台中打印缩进的代码。就是这样

© www.soinside.com 2019 - 2024. All rights reserved.