Program to check whether the given string is a binary string or not

Introduction

In this section of python programming, we will check whether the given input is binary string or not. A binary string is a sequence of numbers 0 and 1. Any other number other than 0 and 1 are not included in the binary string.

Program to check whether the given string is a binary string or not using Python

Program

def ck_binary(x):
# Converting input value into set
    ip_set = set(x)
# Declaring new set with values 0 and 1
    bin_set = { '0', '1'}
# Check if input string elements is 0 , 1
    if bin_set == ip_set or ip_set == {'0'} or ip_set == {'1'}:
        print("The string {0} is binary string!".format(x))
    else:
        print("The string {0} is not a binary string!".format(x))
ip_str = input("Enter the string to check whether it's a binary string : ")


ck_binary(ip_str)

 

Output 1:  String is not binary string

Program to check whether the given string is a binary string or not Output 1 

 

Output 2: String is a binary string

Program to check whether the given string is a binary string or not Output 2 

Explanation

To achieve the result of our task, we converted the input string into set to get the unique characters in the string. And also we have declared a set with values 0 and 1. To check whether the string is binary, if the input string set is equalled to the new set or equalled to ‘ 0 ‘ or ‘ 1 ‘. The value is printed on the screen depending upon the condition satisfied.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.