Hundurinn Nero
Hundurinn Nero

Reputation: 83

How to count ending 0s in binary string

I have this string: 11000000101010000000010000000000

I would like to count the 0s starting at the back until I hit 1 and stop there, determining the total number of 0s at the end. In this particular case it would give me 10 as an answer.

Any help greatly appreciated.

Upvotes: 1

Views: 183

Answers (6)

Siva Cn
Siva Cn

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

TerryA
TerryA

Reputation: 59974

Use str.rsplit() and str.count()

>>> s = '11000000101010000000010000000000'
>>> len(s.rsplit('1', 1)[-1])
10

Upvotes: 5

Trevor Merrifield
Trevor Merrifield

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

erewok
erewok

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

SylvainD
SylvainD

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

arshajii
arshajii

Reputation: 129517

You can use rindex() to get the index of the last 1 and then subtract that from the maximum index (len(s) - 1):

>>> s = '11000000101010000000010000000000'
>>> len(s) - s.rindex('1') - 1
10

Upvotes: 6

Related Questions