Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a string has exactly 8 1's and 0's in it in python

Tags:

python

I want to return a boolean value True or False depending on if the string contains only 1's and 0's.

The string has to be composed of 8 1's or 0's and nothing else.

If it only contains 1's or 0's, it will return True and if not it will return False.

def isItBinary(aString):
    if aString == 1 or 0:
        return True
    else:
        return False

This is what I have so far but I'm just not sure how to compare it to both of the numbers as well as see if it has a length of 8 1's and 0's.

like image 332
wahlysadventures Avatar asked Oct 22 '15 16:10

wahlysadventures


3 Answers

You can use all for this and check the length to make sure it is exactly 8.

all(c in '10' for c in aString) and len(aString) == 8

Example:

aString = '11110000'
all(c in '10' for c in aString) and len(aString) == 8
>>> True

The main benefit of doing this over other methods is that it will short-circuit if it finds anything but a zero or one.

like image 138
Eric Hotinger Avatar answered Sep 29 '22 07:09

Eric Hotinger


You can use set here. Example -

def isItBinary(aString):
    seta = set(aString)
    if seta.issubset('10') and len(aString) == 8:
        reutrn True
    return False
like image 25
Sharon Dwilif K Avatar answered Sep 29 '22 08:09

Sharon Dwilif K


len(aString) == 8 and set(aString) <= {"0", "1"}

The operator <= means “is a subset of” here.

like image 41
user87690 Avatar answered Sep 29 '22 08:09

user87690