
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Given String Is a Binary String in Python
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 = 0 for char in stringA: if char not in b: count = 1 break else: pass if 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: pass if 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 string StringB is not a binary string