简体   繁体   中英

How to check the given input is binary number or not?

I need to write a logic to print message like it's a binary or it's not a binary

Input 1: 100001

Input 2: 001

Input 3: 101

I have written below code:

n=str(input('enter the number'))

if len(n) == 8:
   print("it's a binary")
else:
   print("it's not a binary")

Seems like this is not a right approach any other way to identify

Output 1: It's a binary

Output 2: It's a binary

Output 3: It's a binary

101, 001 -> if padded with zero from left then it becomes 8 digit binary number

Invalid binary numbers: 254, 66, 72, 1056

Binary should contain only 1 and 0

Try using sets, it should make it easy. A set will take the unique items of your string, thus for a binary number you can match for 0 and 1 as strings in a set.

The "pipe" or the "or" operation will join the sets and if there's anything more than the set of zeroes and ones, it'll fail.

Notice it'll be true on an empty input, for that check for If text and... . ( (set()|{'0', '1'}) == {'0', '1'} ]

Alternatively set.issubset() should be a replacement for the == operator, if that suits you better.

text = input()
if (set(text) | {'0', '1'}) == {'0', '1'}:
    print("binary")

You can iterate over the int as a str and check if it only contains '0' and '1' :

n = input()
if not n: # So n is different from '' (empty string)
    print('Not binary')
    return
for i in n:
    if (i not in ['0', '1']):
        print('Not binary')
        return
print('Binary')

Your previous check strategy won't work at all, according to your code:

  • 01234567 -> It's a binary
  • 0101 -> It's not a binary

To check this you can anyway use the re Python library (re stands for regex , reg ular ex pression):

import re
pattern = re.compile('^[0-1]{8}$') # A string made out of 0 and 1 and of lenght 8
if pattern.match(input()):
    print('Binary of lenght 8')
else:
    print('Not a binary of lenght 8')

If you don't care about lenght, you can use set s, a Python's iterable class that doesn't admit duplicate elements in it:

>>> set(['1', '1', '0'])
{'1', '0'}
>>> set('01011010101010')
{'0', '1'}

Then you can write something like this:

if set(input()) in [{'0', '1'}, {'0'}, {'1'}]:
    print('Binary')

As @azro suggested, a better syntax is using set instance method issubset , like this:

if set(input()).issubset({'0'}, {'1'}):
    print('binary')

One approach can be if the string contains either 0 or 1 only then we can conclude it is a binary otherwise not.

given_string = input('enter the number')
# set function convert string into set of characters
p = set(given_string)
 
# declare set of '0', '1'
s = {'0', '1'}
 
# check set p is same as set s or set p contains only '0'
# or set p contains only '1'or not, if any one condition
# is true then string is accepted otherwise not accepted
if s == p or p == {'0'} or p == {'1'}:
        print("Yes")
else :
        print("No")

Alternatively you can try the issubset method of set using the following approach:

given_string = input('enter the number')
x = {"0", "1"}
y = set(given_string)
if y.issubset(x): 
      print("Binary")
else:
      print("Not Binary")

Try this:

n = input('enter the number: ') # `n` is already of type `str`
if all(c in '01' for c in n):
    print("it's a binary")
else:
    print("it's not a binary")

In case to check for an 8 bit binary

import re
pattern = re.compile("^([0-1]{8})$")
strings=[
    "00000001",
    "12345678",
    "101",
]
for string in strings:
    if pattern.match(string):
        print(f"{string} is binary")
    else:
        print(f"{string} is not binary")

Output

00000001 is binary
12345678 is not binary
101 is not binary   

In case the binary number can contain any number of zeros and ones or less use

"^([0-1]+)$"

May be this could help you to get desired output

Code:

import re
a=190
check_values_exist = re.findall('[2-9]+', str(a))

if len(check_values_exist) == 0:
  print("It's binary")
else:
  print("It's not a binary")

Output:

It's not a binary

I would do this as follows:

def is_binary(s):
  # bool(s) guards against the case of s = ""
  return bool(s) and all(c in "01" for c in s)

def is_binary2(s):
  try:
    # check if the builtin int type can parse a binary string
    res = int(s, base=2)
    return True
  except:
    return False

The first approach checks if all digits are 0 or 1, and takes care of the empty string case. The second approach delegates all of the works to the standard library.

  1. Input return a string so the str() is useless
  2. Your outputs are wrong.
  3. Your code return if a str could be a byte.
  4. Here is a code to know if a string is a byte:
def is_binary(n:str) -> bool :
    return len(n) = [for i in n if i == "0" or i == "1"]

def is_byte(n:str) -> bool :
    return is_binary(n) and len(n) = 8

print(is_byte(10010110))
-> True
print(is_byte(100a01c0))
-> False
print(is_byte(101))
-> False

You can also convert str to set to know if it is a binary number;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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