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

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

Leave a Comment