1

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.

6 Answers 6

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

Good, but what about when it is all zeros?
@StevenRumbalski What would you expect the answer to be in that case? Raising an error (which rindex will do) seems most appropriate to me in such cases.
I don't know. Depends on what OP is using the number for. OP may want to return a count of zero, or total length.
5

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

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

3 Comments

To take advantage of rsplit (instead of just split), use the maxsplit argument: s.rsplit('1', 1). Also, no need for count once it's been split. Just use len(s.rsplit('1',1)[-1])
Another alternative: len(s) - len(s.rstrip('0'))
This will give incorrect results if the string doesn't contain any 1s.
2

Here is how to do it in regex, because why not!

>>> s = '11000000101010000000010000000000'
>>> match = re.search('0*$', s)
>>> match.end() - match.start()
10

1 Comment

That was kinda my thinking: why not use a lambda and a couple of generators to answer this one!
1

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

Comments

0

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.

Comments

0
binary_str = "11000000101010000000010000000000"

import re

match_obj = re.search(r"0*$", binary_str)

if match_obj:
    print len(match_obj.group())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.