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.
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.
You can use set
here. Example -
def isItBinary(aString):
seta = set(aString)
if seta.issubset('10') and len(aString) == 8:
reutrn True
return False
len(aString) == 8 and set(aString) <= {"0", "1"}
The operator <=
means “is a subset of” here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With