Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 561
grieve Avatar asked Nov 30 '12 16:11

grieve


People also ask

How do you count spaces in a string?

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.


1 Answers

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 
like image 87
zenpoy Avatar answered Sep 20 '22 07:09

zenpoy