Check if a given string is binary string or not - Python
A binary string is a string that contains only the characters '0' and '1'. For example, "101010" is a binary string, while "10201" is not. Our task is to check if a given string is a binary string or not.
Using all()
all() function in Python is a built-in method that returns True if all elements of an iterable satisfy a given condition, and False otherwise.
s = "101010000111"
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): creates a generator that iterates through each character in s.
- Checks if each character belongs to the set {'0','1'}.
- Short-circuit evaluation: all() stops immediately if a character fails the condition, making it fast for large strings.
Using set()
set() can be used to quickly identify the unique characters in a string.
s = "101010000111"
if set(s).issubset({'0', '1'}):
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- set(s): converts the string into a set of unique characters.
- issubset({'0', '1'}): checks if all unique characters are either '0' or '1'.
- Efficient for strings with repeated characters as it reduces unnecessary checks.
Using Regular Expressions
Regular expressions (regex) provide a powerful and flexible way to match patterns in strings.
import re
s = "101010000111"
if re.fullmatch('[01]+', s):
print("Yes")
else:
print("No")
Output
Yes
Explanation:
- [01]+ matches one or more occurrences of '0' or '1'.
- re.fullmatch(): ensures the entire string matches the pattern.
- Regex is powerful and concise but slightly slower than all() or set-based checks for simple patterns.
Using a for Loop
A simple for loop can iterate through each character of the string and manually check whether it is '0' or '1'.
s = "101010000111"
for char in s:
if char not in '01':
print("No")
break
else:
print("Yes")
Output
Yes
Explanation:
- Iterates through each character, checking membership in '01'.
- Stops immediately when an invalid character is found using break.
- Simple to understand, but concatenation or repeated membership checks are slower than generator-based all().