Open In App

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

Last Updated : 03 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given string str. The task is to check whether it is a binary string or not. 

Examples:  

Input: str = "01010101010"
Output: Yes

Input: str = "geeks101"
Output: No

Approach 1: Using Set  

  1. Insert the given string in a set
  2. Check if the set characters consist of 1 and/or 0 only.

Example:

Python3




# Python program to check
# if a string is binary or not
 
# function for checking the
# string is accepted or not
 
 
def check(string):
 
    # set function convert string
    # into set of characters .
    p = set(string)
 
    # declare set of '0', '1' .
    s = {'0', '1'}
 
    # check set p is same as set s
    # or set p contains only '0'
    # or set p contains only '1'
    # or not, if any one condition
    # is true then string is accepted
    # otherwise not .
    if s == p or p == {'0'} or p == {'1'}:
        print("Yes")
    else:
        print("No")
 
 
# driver code
if __name__ == "__main__":
 
    string = "101010000111"
 
    # function calling
    check(string)


Output

Yes

Time Complexity: O(n), Here n is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.

Approach 2: Simple Iteration 

  1. Iterate for every character and check if the character is 0 or 1.
  2. If it is not then set a counter and break.
  3. After iteration check whether the counter is set or not.

Python3




# Python program to check
# if a string is binary or not
 
# function for checking the
# string is accepted or not
 
 
def check2(string):
 
    # initialize the variable t
    # with '01' string
    t = '01'
 
    # initialize the variable count
    # with 0 value
    count = 0
 
    # looping through each character
    # of the string .
    for char in string:
 
        # check the character is present in
        # string t or not.
        # if this condition is true
        # assign 1 to the count variable
        # and break out of the for loop
        # otherwise pass
        if char not in t:
            count = 1
            break
        else:
            pass
 
    # after coming out of the loop
    # check value of count is non-zero or not
    # if the value is non-zero the en condition is true
    # and string is not accepted
    # otherwise string is accepted
    if count:
        print("No")
    else:
        print("Yes")
 
 
# driver code
if __name__ == "__main__":
 
    string = "001021010001010"
 
    # function calling
    check2(string)


Output

No

Time Complexity: O(n), Here n is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.

Approach 3: Regular Expressions

  1. Compile a regular expression using compile() for “character is not 0 or 1”.
  2. Use re.findall() to fetch the strings satisfying the above regular expression.
  3. Print output based on the result.

Python3




#import library
import re
 
sampleInput = "1001010"
 
# regular expression to find the strings
# which have characters other than 0 and 1
c = re.compile('[^01]')
 
# use findall() to get the list of strings
# that have characters other than 0 and 1.
if(len(c.findall(sampleInput))):
    print("No") # if length of list > 0 then it is not binary
else:
    print("Yes") # if length of list = 0 then it is binary


Output

Yes

Time complexity: O(n)
Auxiliary space: O(1)

Approach 4: Using exception handling and int

Python has a built in method to convert a string of a specific base to a decimal integer, using int(string, base). If the string passed as an argument is not of the specified base, then a ValueError is raised.

Python3




# Python program to check
# if a string is binary or not
 
# function for checking the
# string is accepted or not
 
 
def check(string):
    try:
        # this will raise value error if
        # string is not of base 2
        int(string, 2)
    except ValueError:
        return "No"
    return "Yes"
 
 
# driver code
if __name__ == "__main__":
 
    string1 = "101011000111"
    string2 = "201000001"
 
    # function calling
    print(check(string1))
    print(check(string2))
 
 
# this code is contributed by phasing17


Output

Yes
No

Time Complexity: O(1), 
Auxiliary Space: O(1)

Approach 5 : Using count() function

Python3




string = "01010101010"
if(string.count('0')+string.count('1')==len(string)):
    print("Yes")
else:
    print("No")


Output

Yes

Time Complexity: O(n), where n is number of characters in string.
Auxiliary Space: O(1)

Approach 6 : Using replace() and len() methods

Python3




#Python program to check string is binary or not
string = "01010121010"
binary="01"
for i in binary:
    string=string.replace(i,"")
if(len(string)==0):
    print("Yes")
else:
    print("No")


Output

No

Approach 7: Using all()

The all() method in Python3 can be used to evaluate if all the letters in the string are 0 or 1.

Python3




# Python program to check
# if a string is binary or not
 
# function for checking the
# string is accepted or not
 
 
def check(string):
    if all((letter in "01") for letter in string):
        return "Yes"
    return "No"
 
 
# driver code
if __name__ == "__main__":
 
    string1 = "101011000111"
    string2 = "201000001"
 
    # function calling
    print(check(string1))
    print(check(string2))
 
 
# this code is contributed by phasing17


Output

Yes
No

Time Complexity: O(n), Here n is the length of the string.
Auxiliary Space: O(1), As constant extra space is used.

Approach 8: Using issubset() method 

We can use a issubset method in comprehension to check if all characters in the string are either 0 or 1.

Python3




def is_binary_string(s):
    # use set comprehension to extract all unique characters from the string
    unique_chars = {c for c in s}
    # check if the unique characters are only 0 and 1
    return unique_chars.issubset({'0', '1'})
 
# driver code
if __name__ == "__main__":
   
    string1 = "101011000111"
    string2 = "201000001"
   
    # function calling
    print(is_binary_string(string1))
    print(is_binary_string(string2))


Output

True
False

Time complexity: O(n), where n is the length of the input string, and 
 Auxiliary space: O(1).

Method: Using re.search() 

  1. Import the re module.
  2. Define a regular expression that matches any character other than ‘0’ and ‘1’.
  3. Use the re.search() method to search for the regular expression in the given string.
  4. If a match is found, then the given string is not a binary string. Otherwise, it is.

Python3




import re
 
def is_binary_string(str):
    # Define regular expression
    regex = r"[^01]"
     
    # Search for regular expression in string
    if re.search(regex, str):
        return False
    else:
        return True
 
#Examples
print(is_binary_string("01010101010"))   # Output: Yes
print(is_binary_string("geeks101"))   # Output: No


Output

True
False

Time Complexity: O(n), where n is the length of the given string (as we are iterating over the string once).

Auxiliary Space: O(1)



Similar Reads

Program to check if a matrix is Binary matrix or not
Given a matrix, the task is to check if that matrix is a Binary Matrix. A Binary Matrix is a matrix in which all the elements are either 0 or 1. It is also called Logical Matrix, Boolean Matrix, Relation Matrix. Examples: Input: {{1, 0, 1, 1}, {0, 1, 0, 1} {1, 1, 1, 0}} Output: Yes Input: {{1, 0, 1, 1}, {1, 2, 0, 1}, {0, 0, 1, 1}} Output: No Approa
5 min read
Lexicographically smallest binary string formed by flipping bits at indices not divisible K1 or K2 such that count of 1s is always greater than 0s from left
Given a binary string S(1-based indexing) of size N, and two positive integers K1 and K2, the task is to find the lexicographically smallest string by flipping the characters at indices that are not divisible by either K1 or K2 such that the count of 1s till every possible index is always greater than the count of 0s. If it is not possible to form
8 min read
Pratul Kumar - Geek on the top | Learning is not a race, so it should not be treated like same
Geek on the top is all about success stories of Geeks who are working hard to chase their goals and are the inspiration for other geeks. Pratul Kumar is a prefinal year student from LNMIIT and is working as a Google Summer of Code(GSoC) developer at SugarLabs. Pratul has started a PyJaipur community with thought to organize local meetup where learn
8 min read
Check if a given string is sum-string
Given a string of digits, determine whether it is a ‘sum-string’. A string S is called a sum-string if the rightmost substring can be written as the sum of two substrings before it and the same is recursively true for substrings before it. Examples: “12243660” is a sum string. Explanation : 24 + 36 = 60, 12 + 24 = 36 “1111112223” is a sum string. E
12 min read
8085 program to check whether both the nibbles of 8 bit number are equal or not
Problem - Write an assembly language program in 8085 microprocessor to check whether both the nibbles of 8 bit number are equal or not. If nibbles are equal then store 00 in memory location 3050 otherwise store FF in memory location 3050. Example - Assumption - Number, to check for similar nibbles is stored at memory location 2050. Algorithm - Load
3 min read
Recursive program to check if number is palindrome or not
Given a number, the task is to write a recursive function that checks if the given number is a palindrome or not. Examples: Input: 121Output: yes Input: 532Output: no The approach for writing the function is to call the function recursively till the number is wholly traversed from the back. Use a temp variable to store the reverse of the number acc
4 min read
Check if an array can be split into 3 subsequences of equal sum or not
Given an array arr[] having N integers. The task is to determine if the array can be partitioned into 3 subsequences of an equal sum or not. If yes then print “Yes”. Otherwise, print “No”. Examples: Input: arr[] = {1, 1, 1}Output: YesExplanation:Here array can be partition into 3 equal sum. {1} Input: arr[] = {40}Output: NoExplanation:Here array ca
15+ min read
To check a number is palindrome or not without using any extra space
Given a number 'n' and our goal is to find out it is palindrome or not without using any extra space. We can't make a new copy of the number . Examples: Input : 2332 Output : Yes it is Palindrome. Explanation: original number = 2332 reversed number = 2332 Both are same hence the number is palindrome. Input :1111 Output :Yes it is Palindrome. Input
6 min read
Check if a number is power of 8 or not
Given a number check whether it is a power of 8 or not. Examples : Input : n = 64 Output : Yes Input : 75 Output : NoRecommended PracticeCheck if a Integer is power of 8 or notTry It! First solution We calculate log8(n) of the number if it is an integer, then n is in the power of 8. We use trunc(n) function that finds the closest integer for a doub
9 min read
Check if Email Address is Valid or not in Java
Given a string, find if the given string is a valid email or not. Input : email = "review-team@geeksforgeeks.org" Output : Yes Input : email = "contribute@geeksforgeeks..org" Output : No Explanation : There is an extra dot(.) before org. Prerequisite: Regular Expressions in Java Regular Expressions Regular Expressions or Regex is an API for definin
2 min read
Article Tags :
Practice Tags :