Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the length of a leading sequence in a string?

Tags:

python

string

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
like image 531
Mark Harrison Avatar asked Dec 03 '22 17:12

Mark Harrison


1 Answers

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
like image 101
Bhargav Rao Avatar answered Dec 05 '22 05:12

Bhargav Rao