Grab a line's whitespace/indention with Python

前端 未结 6 1750
轮回少年
轮回少年 2020-12-06 10:48

Basically, if I have a line of text which starts with indention, what\'s the best way to grab that indention and put it into a variable in Python? For example, if the line i

6条回答
  •  庸人自扰
    2020-12-06 11:08

    This can also be done with str.isspace and itertools.takewhile instead of regex.

    import itertools
    
    tests=['\t\tthis line has two tabs of indention',
           '    this line has four spaces of indention']
    
    def indention(astr):
        # Using itertools.takewhile is efficient -- the looping stops immediately after the first
        # non-space character.
        return ''.join(itertools.takewhile(str.isspace,astr))
    
    for test_string in tests:
        print(indention(test_string))
    

提交回复
热议问题