How to Check if a String is a Binary String in Python
In this tutorial, we’ll learn how to program “How to Check if a String is a Binary String in Python.” The objective is to safely check whether a string represents a binary number. This tutorial will guide you through the proper method for determining if a string is binary. So, let’s get started!
This topic is straightforward to understand. Just follow the instructions I provide, and you’ll complete it with ease. The program I’ll demonstrate will illustrate the correct way to check if a string is a binary number. So, let’s dive into the coding process!
Getting Started:
First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.
Creating Main Function
This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.- import re
- while True:
- print("\n================= Check if a String is a Binary String =================\n\n")
- s = input("Enter a number: ")
- if re.fullmatch('[01]+', s):
- print("This is a binary number!")
- else:
- print("This is not a binary number!")
- opt = input("\nDo you want to try again?(yes/no): ")
- if opt.lower() == 'yes':
- ret=False
- elif opt.lower() == 'no':
- ret=True
- print("Exiting program....")
- else:
- print("Please enter yes/no:")
- break
- if ret == False:
- continue
This program checks whether a given string consists only of binary digits (0s and 1s) using regular expressions. If the string matches the pattern [01]+, it is classified as a binary number; otherwise, it is not. The program then asks the user if they want to try again or exit.
Output:

There you have it we successfully created How to Check if a String is a Binary String in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for Python Language