How to determine that a string has exactly 8 1 and 0 in it in python

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

The string should consist of 8 1 or 0 and nothing else.

If it contains only 1 or 0, it will return True , and if it does not 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 with both numbers, and also see if it has a length of 8 1 and 0.

+5
source share
6 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 advantage of this method is that it will close if it finds anything but zero or one.

+6
source

You can use set . Example -

 def isItBinary(aString): seta = set(aString) if seta.issubset('10') and len(aString) == 8: reutrn True return False 
+2
source
 len(aString) == 8 and set(aString) <= {"0", "1"} 

The operator <= means that "is a subset" here.

+2
source

try the following:

 def isItBinary(aString): return all([char in '01' for c in aString]+[len(aString)==8]) 
+1
source

I like lambda over for loops

 >>> str = '10001010' >>> len(str) == 8 and len(filter(lambda bool: not bool, map(lambda bit: bit in '01', str))) == 0 True 
+1
source

If your string should represent an 8-bit binary number, you can try converting it as such to your test:

 def isItBinary(s): try: return len(s)==8 and int(s,2) < 256 except ValueError: return False 
+1
source

Source: https://habr.com/ru/post/1234299/


All Articles