【发布时间】:2013-07-29 12:12:06
【问题描述】:
我的目标是确定 python 文件中代码行的确切缩进。由于我将在某个位置检测语句,因此确定行所需的缩进对于实现我的目标很重要。这个问题可以用下面的例子来解释:
First Scenario
#A.py
a=0 <----------- indentation '0' spaces or '0' \t
while a<5: <----------- indentation '0' spaces or '0' \t
print a <----------- indentation '4' spaces or '1' \t
a=a+1 <----------- indentation '4' spaces or '1' \t
Second scenario
#A.py
a=0 <----------- indentation '0' spaces or '0' \t
while a<5: <----------- indentation '0' spaces or '0' \t
print a <----------- indentation '8' spaces or '2' \t
a=a+1 <----------- indentation '8' spaces or '2' \t
由于我正在检查由许多文件组成的应用程序,因此我遇到了具有上述情况的文件。我想知道如何确定 python 文件中任何行的缩进?
【问题讨论】:
-
您可以阅读该行,然后使用
lstrip()修剪前导空格并将新字符串大小与具有前导空格的大小进行比较。 -
这就是疯狂。无需测量那里有什么,只需将其全部更改为一致,这样您就无需再猜测了。
-
如果您正在使用任何源代码,那么您必须接受解析器接受的任何内容。
-
我认为他正在尝试构建一个 linting 或代码分析工具。不需要居高临下的cmets。
-
@MarkusUnterwaditzer 我认为没有人的 cmets 居高临下吗?还是评论被删除了?
标签: python indentation