Check string indentation?

↘锁芯ラ 提交于 2019-11-30 08:50:33

问题


I'm building an analyzer for a series of strings. I need to check how much each line is indented (either by tabs or by spaces).

Each line is just a string in a text editor. How do I check by how much a string is indented?

Or rather, maybe I could check how much whitespace or \t are before a string, but I'm unsure of how.


回答1:


To count the number of spaces at the beginning of a string you could do a comparison between the left stripped (whitespace removed) string and the original:

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

Tab indent is context specific... it changes based on the settings of whatever program is displaying the tab characters. This approach will only tell you the total number of whitespace characters (each tab will be considered one character).

Or to demonstrate:

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

EDIT:

If you want to do this to a whole file you might want to try

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



回答2:


I think Gizmo's basic idea is good, and it's relatively easy to extend it to handle any mixture of leading tabs and spaces by using a string object's expandtabs() method:

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")

The last two print statements will output the same value.

Edit: I modified it to check and return 0 if a line of all tabs and spaces is encountered.




回答3:


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


来源:https://stackoverflow.com/questions/13241399/check-string-indentation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!