'Would anyone know the code in python that prints ONLY if it's a binary string? Thanks in advance [closed]
The real problem is there: write a program that takes a string as input and prints “Binary Number” if the string contains only 0s or 1s. Otherwise, print “Not a Binary Number”.
Solution 1:[1]
It is easy.
def is_binary(string_to_check:str):
for x in string_to_check: #loop though all letter
if x in ('0','1'):
continue #yep the letter is binary thingy
else:
return False #no
return True #yep the string is binary
Next time check google before ask.
Solution 2:[2]
def check_if_binary(string) :
p = set(string)
s = {'0', '1'}
if s == p or p == {'0'} or p == {'1'}:
print("Binary Number")
else :
print("Not a Binary Number")
string = str(input ("Enter the sting : "))
check_if_binary(string)
References: https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BrainFl |
| Solution 2 |
