Categories
Python Answers

How to check if a string is binary with Python?

Spread the love

We can check if a string is binary in Python by iterating through each character in the string and verifying if it’s either ‘0’ or ‘1’. Here’s a simple function to do that:

def is_binary(s):
    for char in s:
        if char != '0' and char != '1':
            return False
    return True

# Example usage:
string1 = "101010101"  # binary string
string2 = "10101012"   # non-binary string

print(is_binary(string1))  # Output: True
print(is_binary(string2))  # Output: False

This function iterates through each character in the input string s.

If any character is not ‘0’ or ‘1’, it returns False, indicating that the string is not binary. If all characters are ‘0’ or ‘1’, it returns True, indicating that the string is binary.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *