Check if a given string is binary string or not - Python
Last Updated :
03 Mar, 2025
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.
Python
import re
s = "101010000111"
# check if string matches binary pattern
if re.fullmatch('[01]+', s):
print("Yes")
else:
print("No")
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'".
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.
Python
s = "101010000111"
# check if all characters are '0' or '1'
if all(c in '01' for c in s):
print("Yes")
else:
print("No")
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.
Python
s = "101010000111"
# convert string into a set of characters
if set(s).issubset({'0', '1'}):
print("Yes")
else:
print("No")
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.
Python
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")
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.
Similar Reads
Python Set | Check whether a given string is Heterogram or not Given a string S of lowercase characters. The task is to check whether a given string is a Heterogram or not using Python. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Input1: S = "the big dwarf only jumps"Output1: YesExplanation: Each alphabe
3 min read
Check if String Contains Substring in Python This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
8 min read
Convert binary to string using Python We are given a binary string and need to convert it into a readable text string. The goal is to interpret the binary data, where each group of 8 bits represents a character and decode it into its corresponding text. For example, the binary string '01100111011001010110010101101011' converts to 'geek'
3 min read
Python - Check if there are K consecutive 1's in a binary number The task is to check if a binary number (a string of 0s and 1s) has k consecutive 1s in it. The goal is to figure out if this pattern exists in the easiest and fastest way possible. Using for loopThis method works by going through the string once and keeping track of how many '1's appear in a row. I
3 min read
Check If String is Integer in Python In this article, we will explore different possible ways through which we can check if a string is an integer or not. We will explore different methods and see how each method works with a clear understanding.Example:Input2 : "geeksforgeeks"Output2 : geeksforgeeks is not an IntigerExplanation : "gee
4 min read
Check if given number contains only â01â and â10â as substring in its binary representation Given a number N, the task is to check if the binary representation of the number N has only "01" and "10" as a substring or not. If found to be true, then print "Yes". Otherwise, print "No".Examples: Input: N = 5 Output: Yes Explanation: (5)10 is (101)2 which contains only "01" and "10" as substrin
6 min read
How to find the int value of a string in Python? In Python, we can represent an integer value in the form of string. Int value of a string can be obtained by using inbuilt function in python called as int(). Here we can pass string as argument to this function which returns int value of a string. int() Syntax : int(string, base) Parameters : strin
2 min read
Check if both halves of the string have same set of characters in Python Given a string of lowercase characters only, the task is to check if it is possible to split a string from middle which will gives two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the res
3 min read
Convert String to Int in Python In Python, converting a string to an integer is important for performing mathematical operations, processing user input and efficiently handling data. This article will explore different ways to perform this conversion, including error handling and other method to validate input string during conver
3 min read
Python Dictionary | Check if binary representations of two numbers are anagram Given two numbers you are required to check whether they are anagrams of each other or not in binary representation. Examples: Input : a = 8, b = 4 Output : YesBinary representations of bothnumbers have same 0s and 1s.Input : a = 4, b = 5Output : NoCheck if binary representations of two numbersWe ha
3 min read