Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python trick in finding leading zeros in string

Tags:

python

I have a binary string say '01110000', and I want to return the number of leading zeros in front without writing a forloop. Does anyone have any idea on how to do that? Preferably a way that also returns 0 if the string immediately starts with a '1'

like image 942
user2008886 Avatar asked Jan 24 '13 20:01

user2008886


2 Answers

Here is another way:

In [36]: s = '01110000'

In [37]: len(s) - len(s.lstrip('0'))
Out[37]: 1

It differs from the other solutions in that it actually counts the leading zeroes instead of finding the first 1. This makes it a little bit more general, although for your specific problem that doesn't matter.

like image 191
NPE Avatar answered Sep 28 '22 05:09

NPE


I'd use:

s = '00001010'
sum(1 for _ in itertools.takewhile('0'.__eq__, s))

Rather pythonic, works in the general case, for example on the empty string and non-binary strings, and can handle strings of any length (or even iterators).

like image 32
user511824 Avatar answered Sep 28 '22 05:09

user511824