Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • 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 for ASCII String - Python
Next article icon

Python – Check for spaces in string

Last Updated : 16 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sometimes, while working with strings in Python, we need to determine if a string contains any spaces. This is a simple problem where we need to check for the presence of space characters within the string. Let’s discuss different methods to solve this problem.

Using ‘in’ operator

‘in’ operator is one of the simplest and most efficient ways to check for spaces in a string. It checks whether a specific character or substring is present in the string.

Python
s = "geeks for geeks" res = " " in s print(res)  

Output
True 

Explanation:

  • We define the string ‘s’.
  • The ‘in’ operator checks if there is a space in ‘s’.
  • The result is stored in res and printed.

Using any() and isspace()

We can use the any() function along with the isspace() method to check for spaces in a string. This method iterates through all the characters in the string and returns True if any of them is a space.

Python
s = "geeks for geeks" res = any(c.isspace() for c in s) print(res)  

Output
True 

Explanation:

  • We define the string ‘s’.
  • The isspace() method checks if each character in the string is a space.
  • The any() function returns True if any character is a space.

Using count()

count() method can be used to check how many spaces are present in a string. If the count is greater than 0, the string contains spaces.

Python
s = "geeks for geeks" res = s.count(" ") > 0 print(res)  

Output
True 

Explanation:

  • We use the count() method to count the number of spaces in the string txt.
  • The result is checked against 0 to determine if there are any spaces.

Using regular expressions

We can use the re.search() method to check for spaces in the string.

Python
import re  s = "geeks for geeks" res = bool(re.search(r"\s", s)) print(res)  

Output
True 

Explanation:

  • We import the re module and define the string ‘s’.
  • re.search() method looks for any whitespace character in the string.
  • result is converted to a boolean using the bool function and printed.

Using a loop

We can manually iterate through the string using a for loop to check for spaces.

Python
s = "geeks for geeks"   res = False  # Initializing a variable to store the result  # Iterating through each character in the string for c in s:     if c == " ":  # Checking if the current character is a space         res = True  # Setting the result to True if a space is found         break  # Exiting the loop as we found a space print(res)  

Output
True 

Explanation:

  • We initialize the variable res to False.
  • Using a loop, we iterate through each character in ‘s’.
  • If a space is found, we set res to True and break the loop.


Next Article
Check for ASCII String - Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Remove spaces from a string in Python
    Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so: Using replace() methodTo remove all spaces from a
    2 min read
  • Python - Check if string repeats itself
    Checking if a string repeats itself means determining whether the string consists of multiple repetitions of a smaller substring. Using slicing and multiplicationWe can check if the string is a repetition of a substring by slicing and reconstructing the string using multiplication. [GFGTABS] Python
    3 min read
  • Python | Check for Whitespace in List
    Sometimes, we might have a problem in which we need to check if the List of strings has any of blank spaces. This kind of problem can be in Machine Learning domain to get specific type of data set. Let’s discuss certain ways in which this kind of problem can be solved. Method #1: Using regex + any()
    4 min read
  • Python Check If String is Number
    In Python, there are different situations where we need to determine whether a given string is valid or not. Given a string, the task is to develop a Python program to check whether the string represents a valid number. Example: Using isdigit() Method [GFGTABS] Python # Python code to check if strin
    6 min read
  • Check for ASCII String - Python
    To check if a string contains only ASCII characters, we ensure all characters fall within the ASCII range (0 to 127). This involves comparing each character's value to ensure it meets the criteria. Using str.isascii()The simplest way to do this in Python is by using the built-in str.isascii() method
    2 min read
  • Python - Avoid Spaces in string length
    When working with strings in Python, we may sometimes need to calculate the length of a string excluding spaces. The presence of spaces can skew the length when we're only interested in the number of non-space characters. Let's explore different methods to find the length of a string while ignoring
    3 min read
  • Python - String Split including spaces
    String splitting, including spaces refers to breaking a string into parts while keeping spaces as separate elements in the result. Using regular expressions (Most Efficient)re.split() function allows us to split a string based on a custom pattern. We can use it to split the string while capturing th
    3 min read
  • Python | Exceptional Split in String
    Sometimes, while working with Strings, we may need to perform the split operation. The straightforward split is easy. But sometimes, we may have a problem in which we need to perform split on certain characters but have exceptions. This discusses split on comma, with the exception that comma should
    4 min read
  • Check if String is Empty or Not - Python
    We are given a string and our task is to check whether it is empty or not. For example, if the input is "", it should return True (indicating it's empty), and if the input is "hello", it should return False. Let's explore different methods of doing it with example: Using Comparison Operator(==)The s
    2 min read
  • Split strings ignoring the space formatting characters - Python
    Splitting strings while ignoring space formatting characters in Python involves breaking a string into components while treating irregular spaces, tabs (\t), and newlines (\n) as standard separators. For example, splitting the string "Hello\tWorld \nPython" should result in ['Hello', 'World', 'Pytho
    3 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