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?
To count the spaces in a string:Use the split() method to split the string on each space. Access the length property on the array and subtract 1. The result will be the number of spaces in the 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With