Check if a given string is binary string or not – Python
The task of checking whether a given string is a binary string in Python involves verifying that the string contains only the characters ‘0’ and ‘1’. A binary string is one that is composed solely of these two digits and no other characters are allowed. For example, the string “101010” is a valid binary string, while “10201” is not, since it contains a character other than ‘0’ or ‘1’.
Using regular expression
Regular expressions provide a powerful way to match patterns in a string. For checking if a string is binary, the regex pattern [01]+ ensures that the string consists solely of ‘0’ and ‘1’. This method is highly efficient, concise and ideal for pattern-based checks.
import re
s = "101010000111"
# check if string matches binary pattern
if re.fullmatch('[01]+', s):
print("Yes")
else:
print("No")
Output
Yes
Explanation: re.fullmatch(‘[01]+’, s) checks if the entire string s consists only of ‘0’ and ‘1’. The [01]+ pattern means “one or more characters that are either ‘0’ or ‘1’”.
Table of Content
Using all()
all() function combined with a generator expression efficiently checks whether every character in the string is either ‘0’ or ‘1’. It stops as soon as a non-binary character is encountered, making it an optimal solution for this task.
s = "101010000111"
# check if all characters are '0' or '1'
if all(c in '01' for c in s):
print("Yes")
else:
print("No")
Output
Yes
Explanation: all(c in ’01’ for c in s) checks each character c in the string s to ensure it’s either ‘0’ or ‘1’. The all() function returns True only if all characters satisfy this condition and it stops early if an invalid character is found.
Using set()
By converting the string into a set of characters, we can quickly verify whether the set of characters is a subset of {‘0’, ‘1’}. This method is both straightforward and efficient, as it leverages the power of Python’s set operations to validate the binary nature of the string.
s = "101010000111"
# convert string into a set of characters
if set(s).issubset({'0', '1'}):
print("Yes")
else:
print("No")
Output
Yes
Explanation: issubset({‘0’, ‘1’}) checks if all characters in the set are either ‘0’ or ‘1’. If the set only contains ‘0’ and ‘1’, the string is binary.
Using for loop
This method manually iterates over each character of the string, checking if it’s either ‘0’ or ‘1’. It’s a simple approach, but efficient as it stops immediately when an invalid character is found, avoiding unnecessary checks.
s = "101010000111"
# check if all characters are '0' or '1'
for char in s:
if char not in '01':
print("No")
break
else:
print("Yes")
Output
Yes
Explanation: if char not in ’01’ checks if the current character is not ‘0’ or ‘1’. If it’s not, the program immediately prints “No” and stops further checks using break.