How would I make an if/else statement where the if checks whether a variable 8 digit variable is in binary? I know how to do the 8 digit part (len()) but I can't work out how to restrict it to 1s and 0s.
6 Answers
You can use a generator expression and all*:
if len(var) == 8 and all(x in "01" for x in var):
...
Below is a demonstration:
>>> var = "01010101"
>>> len(var) == 8 and all(x in "01" for x in var)
True
>>> var = "0101010"
>>> len(var) == 8 and all(x in "01" for x in var)
False
>>> var = "01010102"
>>> len(var) == 8 and all(x in "01" for x in var)
False
>>>
*Note: the above code assumes that var is a string.
Comments
You could try and parse them with int while passing a radix like this:
>>> x = int("10010", 2)
>>> print x
18
Comments
You can use the all() function to test each character:
len(var) == 8 and all(c in '01' for c in var)
or use a set:
binary_digits = set('01')
len(var) == 8 and binary_digits.issuperset(var)
or use a regular expression:
import re
binary_digits = re.compile('^[01]{8}$')
binary_digits.match(, var) is not None
Of these three choices, the regular expression option is the fastest, followed by using a set:
>>> import re
>>> import timeit
>>> def use_all(v): return len(v) == 8 and all(c in '01' for c in v)
...
>>> def use_set(v, b=set('01')): return len(v) == 8 and b.issuperset(v)
...
>>> def use_re(v, b=re.compile('^[01]{8}$')): return b.match(v) is not None
...
>>> binary, nonbinary = '01010101', '01010108'
>>> timeit.timeit('f(binary); f(nonbinary)', 'from __main__ import binary, nonbinary, use_all as f')
4.871071815490723
>>> timeit.timeit('f(binary); f(nonbinary)', 'from __main__ import binary, nonbinary, use_set as f')
2.558954954147339
>>> timeit.timeit('f(binary); f(nonbinary)', 'from __main__ import binary, nonbinary, use_re as f')
2.036846160888672
Comments
I'm going to presume that you also want to convert the string into an integer at some point. If this isn't the case, please correct me.
In Python, it is usually considered better to try to do something, and handle failure if it occurs; rather than checking if something is possible, and only then doing it. This is called the EAFP principle (it is Easier to Ask for Forgiveness than Permission).
In this case, you should use a try except:
s = '01100011'
if len(s) == 8:
try:
n = int(s, 2)
except ValueError:
handle_exception_here()