简体   繁体   English

Python:检查变量是否为二进制

[英]Python: Checking a variable is in binary

How would I make an if/else statement where the if checks whether a variable 8 digit variable is in binary? 我如何在if / else语句中检查if是否检查8位数变量是否为二进制? I know how to do the 8 digit part (len()) but I can't work out how to restrict it to 1s and 0s. 我知道如何做8位数部分(len()),但我不知道如何将其限制为1和0。

To confirm a string contains exactly eight ones and zeros, test it for the regular expression 要确认字符串正好包含八个1和0,请对其进行正则表达式测试

^[01]{8}$

Example of use: 使用示例:

import re
isBin = re.compile('^[01]{8}$')
s1 = "00110101"

if(s1.match(isBin)):
  print "it is a match"
else:
  print "it is not a match"

You can use a generator expression and all *: 您可以使用生成器表达式以及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. *注意:以上代码假定var是一个字符串。

Is the variable encoded as a string, or array of integers? 变量是编码为字符串还是整数数组? You can just do a list comprehension to check each element, other solutions are possible as well. 您只需进行列表理解即可检查每个元素,也可以使用其他解决方案。

isBinary=[x==1 or x==2 for x in variable]
isBinary=False in isBinary

You could try and parse them with int while passing a radix like this: 您可以在传递像这样的基数时尝试使用int解析它们:

>>> x = int("10010", 2)
>>> print x
18

You can use the all() function to test each character: 您可以使用all()函数测试每个字符:

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

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; 在Python中,通常最好尝试做一些事情,并处理失败(如果发生的话)。 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). 这称为EAFP原则(要求宽恕比允许许可容易)。

In this case, you should use a try except : 在这种情况下,你应该使用一个try except

s = '01100011'
if len(s) == 8:
    try:
        n = int(s, 2)
    except ValueError:
        handle_exception_here()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM