Reputation: 83
I have this string: 11000000101010000000010000000000
I would like to count the 0
s starting at the back until I hit 1
and stop there, determining the total number of 0
s at the end. In this particular case it would give me 10
as an answer.
Any help greatly appreciated.
Upvotes: 1
Views: 183
Reputation: 947
binary_str = "11000000101010000000010000000000"
import re
match_obj = re.search(r"0*$", binary_str)
if match_obj:
print len(match_obj.group())
Upvotes: 0
Reputation: 59974
Use str.rsplit()
and str.count()
>>> s = '11000000101010000000010000000000'
>>> len(s.rsplit('1', 1)[-1])
10
Upvotes: 5
Reputation: 4691
Here is how to do it in regex, because why not!
>>> s = '11000000101010000000010000000000'
>>> match = re.search('0*$', s)
>>> match.end() - match.start()
10
Upvotes: 2
Reputation: 7835
I know the question was answered already, but I thought I would add yet another way that you could do this.
You could use itertools.takewhile
on the reverse of the string and takewhile
the digit is not '1'. Apply a sum to all the 1s that were generated and you get the answer.
>>> test = "11000000101010000000010000000000"
>>> sum(1 for x in takewhile(lambda i: i != '1', test[::-1]))
10
Upvotes: 1
Reputation: 1763
You could either :
perform successive divisions by 10 on the corresponding integer taken as if it was in base 10.
use strings operations to find the last 1 and take everything after it
use regular expressions to get the 0s at the end and count them
look for operations to convert to binary and perform successive divisions by two.
Upvotes: 0