What's the shortest way to do this in Python?
string = " xyz"
must return index = 3
What's the shortest way to do this in Python?
string = " xyz"
must return index = 3
>>> next(i for i, j in enumerate(' xyz') if j.strip())
3
or
>>> next(i for i, j in enumerate(' xyz') if j not in string.whitespace)
3
in versions of Python < 2.5 you'll have to do:
(...).next()
>>> string = " xyz"
>>> next(idx for idx, chr in enumerate(string) if not chr.isspace())
3
Looks like the "regexes can do anything" brigade have taken the day off, so I'll fill in:
>>> tests = [u'foo', u' foo', u'\xA0foo']
>>> import re
>>> for test in tests:
... print len(re.match(r"\s*", test, re.UNICODE).group(0))
...
0
1
1
>>>
FWIW: time taken is O(the_answer), not O(len(input_string))
import re
def prefix_length(s):
m = re.match('(\s+)', s)
if m:
return len(m.group(0))
return 0