I'd like to count the number of leading spaces in a string.What's the most Pythonic way of doing this?
>>>F(' ' * 5 + 'a')
5
(update) Here are timings of several of the answers:
import timeit
>>> timeit.timeit("s.index(re.search(r'\S',s).group())", number=10000, setup="import re;s=' a'")
0.027384042739868164
>>> timeit.timeit("len([i for i in itertools.takewhile(str.isspace,s)])", number=10000, setup="import itertools;s=' a'")
0.025166034698486328
>>> timeit.timeit("next(idx for idx,val in enumerate(s) if val != ' ')", number=10000, setup="s=' a'")
0.028306961059570312
>>> timeit.timeit("F(' a')", number=10000, setup="def F(s): return len(s)-len(s.lstrip(' '))")
0.0051808357238769531
Using re
module
>>> s
' a'
>>> import re
>>> s.index(re.search(r'\S',s).group())
5
Using itertools
>>> import itertools
>>> len([i for i in itertools.takewhile(str.isspace,s)])
5
The brute force way
>>> def F(s):
... for i in s:
... if i!=' ':
... return s.index(i)
...
>>> F(s)
5
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