有谁知道 python 中的代码仅当它是二进制字符串时才打印?提前致谢

Would anyone know the code in python that prints ONLY if it's a binary string? Thanks in advance

真正的问题在于: 编写一个程序,将 字符串 作为输入,如果该字符串仅包含 0 或 1,则打印“二进制数”。否则,打印“不是二进制数”。

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)

参考文献:https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/

很简单。

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

下次询问前检查google。

您可以迭代输入的每个字符并验证它是零还是一。 all 函数可用于此迭代和检查。

同时要求字符串至少有一个字符:

def isBinary(string):
    return all(ch in "01" for ch in string) and string != ''

使用示例:

string = input("Enter a binary number: ")
if isBinary(string):
    print("Thank you!")
else:
    print("That is not a binary number.")