In this article we check if a given string has characters which are only 1 or 0. We call such strings as binary strings. If it has any other digit like 2 or 3 etc., we classify it as a non-binary string.
With set
The set operator in python stores only unique elements. So we take a string and apply the set function to it. Then we create another set which has only 0 and 1 as its elements. If both these sets are equal then the string is definitely binary. Also the string may have only 1s or only 0s. So we create a or condition which will also compare the result of set operator only with 0 or only with 1.
Example
stringA = '0110101010111'b = {'0','1'}t = set(stringA)if b == t or t == {'0'} or t == {'1'}:print("StringA is a binary string.")else:print("StringA is not a binary string.")stringB = '0120101010111'u = set(stringB)if b == u or u == {'0'} or u == {'1'}:print("StringB is a binary string.")else:print("StringB is not a binary string.")
Output
Running the above code gives us the following result −
StringA is a binary string.StringB is not a binary string.
With simple iteration
We can first declare a string with value as 01 or 10. Then compare the chraracters of this string with the characters of the given string. If the
Example
stringA = "01100000001"b = '10'count = 0for char in stringA: if char not in b: count = 1 break else: passif count: print("StringA is not a binary string")else: print("StringA is a binary string")stringB = "01200000001"for char in stringB: if char not in b: count = 1 break else: passif count: print("StringB is not a binary string")else: print("StringB is a binary string")
Output
Running the above code gives us the following result −
StringA is a binary stringStringB is not a binary string
Updated on: 10-Jul-2020
6K+ Views
- Related Articles
- Python program to check if a given string is Keyword or not
- Check if a given string is a comment or not
- Check if a string is Isogram or not in Python
- C program to check if a given string is Keyword or not?
- Swift Program to check if a given string is Keyword or not
- Python program to check if a string is palindrome or not
- Check if the Decimal representation of the given Binary String is divisible by K or not
- Check if a binary string contains consecutive same or not in C++
- Python program to check whether a given string is Heterogram or not
- Check if all the 1s in a binary string are equidistant or not in Python
- Check if a binary string has a 0 between 1s or not in C++
- Check if any anagram of a string is palindrome or not in Python
- Program to check given string is anagram of palindromic or not in Python
- C# program to check if a string is palindrome or not
- Java Program to check if a string is empty or not
Advertisem*nts