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

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

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

But is there a more pythonic way?


Solution 1:

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

Solution 2:

You could use itertools.takewhile

sum( 1 for _ in itertools.takewhile(str.isspace,a) )

And demonstrating that it gives the same result as your code:

>>> import itertools
>>> a = "    leading spaces"
>>> print sum( 1 for _ in itertools.takewhile(str.isspace,a) )
4
>>> print "Leading spaces", len(a) - len(a.lstrip())
Leading spaces 4

I'm not sure whether this code is actually better than your original solution. It has the advantage that it doesn't create more temporary strings, but that's pretty minor (unless the strings are really big). I don't find either version to be immediately clear about that line of code does, so I would definitely wrap it in a nicely named function if you plan on using it more than once (with appropriate comments in either case).