python - 嵌套for循环的缩进

标签 python indentation

我想知道为什么这是正确的:

for heading in soup.find_all("td", class_="paraheading"):
    key = " ".join(heading.text.split()).rstrip(":")
    if key in columns:
        print key
        next_td = heading.find_next_sibling("td", class_="bodytext")
        value = " ".join(next_td.text.split())
        print value
    if key == "Industry Categories":
        print key
        ic_next_td = heading.find_next_sibling("td", class_="bodytext")
        for value in ic_next_td.strings:
                print value

这不是:

for heading in soup.find_all("td", class_="paraheading"):
    key = " ".join(heading.text.split()).rstrip(":")
    if key in columns:
        print key
        next_td = heading.find_next_sibling("td", class_="bodytext")
        value = " ".join(next_td.text.split())
        print value
    if key == "Industry Categories":
        print key
        ic_next_td = heading.find_next_sibling("td", class_="bodytext")
        for value in ic_next_td.strings:
            print value

注意第一个代码块中 print value 看似双重缩进。

for value in ic_next_td.strings: 的下一级缩进是否会是该行的一个额外缩进级别?

谢谢

最佳答案

您正在混合使用制表符和空格。不要这样做。

运行 python -tt yourscript.py 以检测任何不一致,但最重要的是,始终使用空格。

将您的编辑器配置为使用空格进行缩进,并将所有现有制表符替换为空格。大多数代码编辑器都有相应的功能。

关于python - 嵌套for循环的缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13453666/

相关文章:

Python通过win32com向Outlook任务添加超链接

string - 新行缩进 Haskell

Vim 缩进折叠依赖

python - 预处理使用 keras 函数 ImageDataGenerator() 生成的图像来训练 resnet50 模型

python - 如何删除 Pandas 的第一行号列?

python - Pandas:导出到 Excel 时如何格式化行和列(行格式优先)?

haskell - Haskell 中的 Let 语法

eclipse - 如何使eclipse不自动缩进一段代码

java - 有没有办法在 Eclipse 中创建一个快捷方式,将光标跳转到当前行的第 n 列?

Python 套接字超时错误