Grab a line's whitespace/indention with Python

前端 未结 6 1746
轮回少年
轮回少年 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:03

    A sneaky way: abuse lstrip!

    fullstr = "\t\tthis line has two tabs of indentation"
    startwhites = fullstr[:len(fullstr)-len(fullstr.lstrip())]
    

    This way you don't have to work through all the details of whitespace!

    (Thanks Adam for the correction)

提交回复
热议问题