Check string indentation?

前端 未结 4 1476
一向
一向 2020-12-18 09:00

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

4条回答
  •  清歌不尽
    2020-12-18 09:56

    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]
    

提交回复
热议问题