What is the pythonic way to count the leading spaces in a string?

前端 未结 6 1758
-上瘾入骨i
-上瘾入骨i 2020-12-03 13:10

I know I can count the leading spaces in a string with this:

>>> a = \"   foo bar baz qua   \\n\"
>>> print \"Leading spaces\", len(a) - le         


        
6条回答
  •  一个人的身影
    2020-12-03 13:46

    Your way is pythonic but incorrect, it will also count other whitespace chars, to count only spaces be explicit a.lstrip(' '):

    a = "   \r\t\n\tfoo bar baz qua   \n"
    print "Leading spaces", len(a) - len(a.lstrip())
    >>> Leading spaces 7
    print "Leading spaces", len(a) - len(a.lstrip(' '))
    >>> Leading spaces 3
    

提交回复
热议问题