Reputation: 111
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'
Upvotes: 11
Views: 16551
Reputation: 335
If you don't know which number would be next to zeros i.e. "1" in this case, and you just want to check if there are leading zeros, you can convert to int and back and compare the two.
"0012300" == str(int("0012300"))
Upvotes: 2
Reputation: 7202
I'm using has_leading_zero = re.match(r'0\d+', str(data))
as a solution that accepts any number and treats 0
as a valid number without a leading zero
Upvotes: 0
Reputation: 990
How about re
module?
a = re.search('(?!0)', data)
then a.start()
is the position.
Upvotes: 0
Reputation: 326
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).
Upvotes: 4
Reputation: 500277
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.
Upvotes: 12
Reputation: 21507
If you're really sure it's a "binary string":
input = '01110000'
zeroes = input.index('1')
Update: it breaks when there's nothing but "leading" zeroes
An alternate form that handles the all-zeroes case.
zeroes = (input+'1').index('1')
Upvotes: 12
Reputation: 5149
A simple one-liner:
x = '01110000'
leading_zeros = len(x.split('1', 1)[0])
This partitions the string into everything up to the first '1' and the rest after it, then counts the length of the prefix. The second argument to split
is just an optimization and represents the number of splits to perform, meaning the function will stop after it found the first '1' instead of splitting it on all occurences. You could just use x.split('1')[0]
if performance doesn't matter.
Upvotes: 9
Reputation: 6448
If you know it's only 0 or 1:
x.find(1)
(will return -1 if all zeros; you may or may not want that behavior)
Upvotes: 3