Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Check if a given string is binary string or not - Python
Next article icon

Check if a given string is binary string or not - Python

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

The task of checking whether a given string is a binary string in Python involves verifying that the string contains only the characters '0' and '1'. A binary string is one that is composed solely of these two digits and no other characters are allowed. For example, the string "101010" is a valid binary string, while "10201" is not, since it contains a character other than '0' or '1'.

Using regular expression

Regular expressions provide a powerful way to match patterns in a string. For checking if a string is binary, the regex pattern [01]+ ensures that the string consists solely of '0' and '1'. This method is highly efficient, concise and ideal for pattern-based checks.

Python
import re  s = "101010000111"  # check if string matches binary pattern if re.fullmatch('[01]+', s):     print("Yes") else:     print("No") 

Output
Yes 

Explanation: re.fullmatch('[01]+', s) checks if the entire string s consists only of '0' and '1'. The [01]+ pattern means "one or more characters that are either '0' or '1'".

Table of Content

  • Using all()
  • Using set()
  • Using for loop

Using all()

all() function combined with a generator expression efficiently checks whether every character in the string is either '0' or '1'. It stops as soon as a non-binary character is encountered, making it an optimal solution for this task.

Python
s = "101010000111"  # check if all characters are '0' or '1' if all(c in '01' for c in s):     print("Yes") else:     print("No") 

Output
Yes 

Explanation: all(c in '01' for c in s) checks each character c in the string s to ensure it’s either '0' or '1'. The all() function returns True only if all characters satisfy this condition and it stops early if an invalid character is found.

Using set()

By converting the string into a set of characters, we can quickly verify whether the set of characters is a subset of {'0', '1'}. This method is both straightforward and efficient, as it leverages the power of Python’s set operations to validate the binary nature of the string.

Python
s = "101010000111"  # convert string into a set of characters if set(s).issubset({'0', '1'}):     print("Yes") else:     print("No") 

Output
Yes 

Explanation: issubset({'0', '1'}) checks if all characters in the set are either '0' or '1'. If the set only contains '0' and '1', the string is binary.

Using for loop

This method manually iterates over each character of the string, checking if it's either '0' or '1'. It's a simple approach, but efficient as it stops immediately when an invalid character is found, avoiding unnecessary checks.

Python
s = "101010000111"  # check if all characters are '0' or '1' for char in s:     if char not in '01':         print("No")         break else:     print("Yes") 

Output
Yes 

Explanation: if char not in '01' checks if the current character is not '0' or '1'. If it’s not, the program immediately prints "No" and stops further checks using break.


Next Article
Check if a given string is binary string or not - Python

P

priyankamaurya
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

    Python Set | Check whether a given string is Heterogram or not
    Given a string S of lowercase characters. The task is to check whether a given string is a Heterogram or not using Python. A heterogram is a word, phrase, or sentence in which no letter of the alphabet occurs more than once. Input1: S = "the big dwarf only jumps"Output1: YesExplanation: Each alphabe
    3 min read
    Check if String Contains Substring in Python
    This article will cover how to check if a Python string contains another string or a substring in Python. Given two strings, check whether a substring is in the given string. Input: Substring = "geeks" String="geeks for geeks"Output: yesInput: Substring = "geek" String="geeks for geeks"Output: yesEx
    8 min read
    Convert binary to string using Python
    We are given a binary string and need to convert it into a readable text string. The goal is to interpret the binary data, where each group of 8 bits represents a character and decode it into its corresponding text. For example, the binary string '01100111011001010110010101101011' converts to 'geek'
    3 min read
    Python - Check if there are K consecutive 1's in a binary number
    The task is to check if a binary number (a string of 0s and 1s) has k consecutive 1s in it. The goal is to figure out if this pattern exists in the easiest and fastest way possible. Using for loopThis method works by going through the string once and keeping track of how many '1's appear in a row. I
    3 min read
    Check If String is Integer in Python
    In this article, we will explore different possible ways through which we can check if a string is an integer or not. We will explore different methods and see how each method works with a clear understanding.Example:Input2 : "geeksforgeeks"Output2 : geeksforgeeks is not an IntigerExplanation : "gee
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences