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

前端 未结 6 1751
-上瘾入骨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:58

    Just for variety, you could theoretically use regex. It's a little shorter, and looks nicer than the double call to len().

    >>> import re
    >>> a = "   foo bar baz qua   \n"
    >>> re.search('\S', a).start() # index of the first non-whitespace char
    3
    

    Or alternatively:

    >>> re.search('[^ ]', a).start() # index of the first non-space char
    3
    

    But I don't recommend this; according to a quick test I did, it's much less efficient than len(a)-len(lstrip(a)).

提交回复
热议问题