检查字符串缩进?

时间:2012-11-05 22:25:46

标签: python indentation analysis lint

我正在为一系列字符串构建分析器。 我需要检查每条线的缩进量(通过制表符或空格)。

每一行只是文本编辑器中的一个字符串。 如何检查字符串缩进多少?

或者更确切地说,也许我可以检查一个字符串前面有多少空格或\ t \ t \ t \ n但是我不确定如何。

4 个答案:

答案 0 :(得分:15)

要计算字符串开头的空格数,您可以在左侧剥离(删除空格)字符串与原始字符串之间进行比较:

a = "    indented string"
leading_spaces = len(a) - len(a.lstrip())
print(leading_spaces) 
# >>> 4

选项卡缩进是特定于上下文的...它会根据显示制表符的任何程序的设置而更改。此方法仅告诉您空白字符的总数(每个选项卡将被视为一个字符)。

或者演示:

a = "\t\tindented string"
leading_spaces = len(a) - len(a.lstrip())
print(leading_spaces)
# >>> 2

编辑:

如果您想对整个文件执行此操作,可能需要尝试

with open("myfile.txt") as afile:
    line_lengths = [len(line) - len(line.lstrip()) for line in afile]

答案 1 :(得分:8)

我认为Gizmo的基本思想很好,通过使用字符串对象的expandtabs()方法扩展它来处理任何前导标签和空格的混合是相对容易的:

def indentation(s, tabsize=4):
    sx = s.expandtabs(tabsize)
    return 0 if sx.isspace() else len(sx) - len(sx.lstrip())

print indentation("  tindented string")
print indentation("\t\tindented string")
print indentation("  \t  \tindented string")

最后两个打印语句将输出相同的值。

编辑:我修改它以检查并在遇到所有标签和空格的行时返回0.

答案 2 :(得分:1)

len()方法会将制表符(\ t)视为一个。在某些情况下,它不会表现出预期的行为。所以我的方法是使用re.sub然后计算空间。

indent_count = re.sub(r'^([\s]*)[\s]+.*$', r'\g<1>', line).count(' ')

答案 3 :(得分:0)

def count_indentation(line) : 
    count = 0 
    try : 
        while (line[count] == "\t") : 
            count += 1 
        return count
    except : 
        return count