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
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
Output 2: String is a binary string
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.
0 Comments