Python - Check if a given string is binary string or not

In this article we check if a given string contains only binary digits (0 and 1). We call such strings binary strings. If the string contains any other characters like 2, 3, or letters, we classify it as a non-binary string.

Using set() Method

The set() function creates a collection of unique characters from a string. We can compare this set with the valid binary characters {'0', '1'} to determine if the string is binary ?

def is_binary_string_set(s):
    binary_chars = {'0', '1'}
    string_chars = set(s)
    return string_chars.issubset(binary_chars) and len(s) > 0

# Test with binary string
stringA = '0110101010111'
if is_binary_string_set(stringA):
    print("StringA is a binary string.")
else:
    print("StringA is not a binary string.")

# Test with non-binary string
stringB = '0120101010111'
if is_binary_string_set(stringB):
    print("StringB is a binary string.")
else:
    print("StringB is not a binary string.")
StringA is a binary string.
StringB is not a binary string.

Using Simple Iteration

We can iterate through each character in the string and check if it belongs to the valid binary characters ('0' or '1'). If any character is not binary, we immediately know the string is not binary ?

def is_binary_string_loop(s):
    binary_chars = '01'
    for char in s:
        if char not in binary_chars:
            return False
    return len(s) > 0

# Test with binary string
stringA = "01100000001"
if is_binary_string_loop(stringA):
    print("StringA is a binary string")
else:
    print("StringA is not a binary string")

# Test with non-binary string
stringB = "01200000001"
if is_binary_string_loop(stringB):
    print("StringB is a binary string")
else:
    print("StringB is not a binary string")
StringA is a binary string
StringB is not a binary string

Using Regular Expressions

Regular expressions provide a concise way to check if a string matches a specific pattern. For binary strings, we can use the pattern ^[01]+$ ?

import re

def is_binary_string_regex(s):
    pattern = r'^[01]+$'
    return bool(re.match(pattern, s))

# Test cases
test_strings = ['0110101', '0120101', '111000', '01a01']

for string in test_strings:
    result = is_binary_string_regex(string)
    print(f"'{string}' is {'binary' if result else 'not binary'}")
'0110101' is binary
'0120101' is not binary
'111000' is binary
'01a01' is not binary

Comparison

Method Time Complexity Best For
set() O(n) Short, readable code
Simple iteration O(n) Early termination on first invalid character
Regular expressions O(n) Complex pattern matching

Conclusion

The set method is most readable, simple iteration is most efficient for invalid strings, and regular expressions work well for complex validation patterns. Choose based on your specific needs and performance requirements.

Updated on: 2026-03-15T18:14:42+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements