Check String is Binary in Python

  • Post category:String

A binary string is a string that contains only 0s and 1s. You can use the following code to check string is binary.

Step 1: Create a string

str = "1010101010"
print("str = ", str)
print("str type = ", type(str))

Step 2: Check if string is binary

if all(c == '0' or c == '1' for c in str):
    print("Binary")
else:
    print("Not Binary")

Output:

str =  1010101010
str type =  <class 'str'>
Binary

Free resources to learn advanced skills: AiHints and CodeAllow