Python | Check for spaces in string
Sometimes, we might have a problem in which we need to check if the string 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
This kind of problem can be solved using the regex utility offered by python. By feeding the appropriate regex string in search(), we can check presence of space in a string.
# Python3 code to demonstrate working of # Check for spaces in string # Using regex import re # initializing string test_str = "Geeks forGeeks" # printing original string print("The original string is : " + test_str) # Using regex # Check for spaces res = bool(re.search(r"\s", test_str)) # printing result print("Does string contain spaces ? " + str(res)) |
The original string is : Geeks forGeeks Does string contain spaces ? True
Method #2 : Using in operator
This task can also be performed using in operator. Just required to check for a space in the string. The verdict returned is true even if a single space is found and false otherwise.
# Python3 code to demonstrate working of # Check for spaces in string # Using in operator # initializing string test_str = "Geeks forGeeks" # printing original string print("The original string is : " + test_str) # Using in operator # Check for spaces res = " " in test_str # printing result print("Does string contain spaces ? " + str(res)) |
The original string is : Geeks forGeeks Does string contain spaces ? True
Recommended Posts:
- Python | Remove spaces from a string
- Python | String Split including spaces
- Python | Remove unwanted spaces from string
- Python code to move spaces to front of string in single traversal
- Python | Check if given string can be formed by concatenating string elements of list
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Check if string ends with any string in given list
- Python | Check if a given string is binary string or not
- Color Spaces in OpenCV | Python
- Python | Remove spaces from dictionary keys
- Python | Remove additional spaces in list
- Python | Visualizing image in different color spaces
- Python | Check for URL in a String
- Regex in Python to put spaces between words starting with capital letters
- Python | Check whether string contains only numbers or not
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


