Wednesday, December 25, 2024
Google search engine
HomeLanguagesPython | Check for spaces in string

Python | Check for spaces in string

Sometimes, we might have a problem in which we need to check if the string has any 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




# 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))


Output : 

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




# 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))


Output : 

The original string is : Geeks  forGeeks
Does string contain spaces ? True

Method #3: Using find() method.

find() method searches the given string for argument passed and returns the position or else returns -1.

Python3




# Python3 code to demonstrate working of
# Check for spaces in string
 
 
# initializing string
test_str = "Geeks forGeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Using in operator
# Check for spaces
res=False
if(test_str.find(" ")!=-1):
    res=True
 
# printing result
print("Does string contain spaces ? " + str(res))


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

Method #4: Using isspace() method
 

Python3




# Python3 code to demonstrate working of
# Check for spaces in string
 
# initializing string
test_str = "Geeks forGeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Check for spaces
c=0
res=False
for i in test_str:
    if(i.isspace()):
        c+=1
if(c>=1):
    res=True
 
# printing result
print("Does string contain spaces ? " + str(res))


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #5: Using count() method:

The count() method is a built-in method in Python that returns the number of occurrences of a specified substring in a string. Here is an example of how to use the count() method to check if a string contains any spaces:
 

Python3




# Python3 code to demonstrate working of
# Check for spaces in string
# Using count() method
 
# initializing string
test_str = "Geeks forGeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Using count() method
# Check for spaces
res = False
if test_str.count(" ") > 0:
    res = True
 
# printing result
print("Does string contain spaces ? " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

In this code, we first initialize a string called “test_str” which contains the text we want to check for spaces. Next, we call the count() method on the string and pass in ” ” (a single space) as the argument.
The count() method returns the number of occurrences of the specified substring in the string.
We check if the number of spaces greater than zero by using if statement, and if it is true then we set the variable res as true.
Finally, we print the result of whether or not the string contains spaces.

Time complexity: O(n)
Auxiliary Space: O(1)

Method #6: Using operator.countOf() method:

Python3




# Python3 code to demonstrate working of
# Check for spaces in string
import operator as op
 
# initializing string
test_str = "Geeks forGeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Using count() method
# Check for spaces
res = False
if op.countOf(test_str, " ") > 0:
    res = True
 
 
print("Does string contain spaces ? " + str(res))
# This code is contributed by vikkycirus


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

Time complexity: O(n)
Auxiliary Space: O(1)

Method#7:Using Recursion

Python3




# Python3 code to demonstrate working of
# Check for spaces in string
# Using Recursion
def ContainSpace(st,i):
  if i == len(st):
    return False
  if st[i] == " ":
    return True
  return ContainSpace(st,i+1)
# initializing string
test_str = "Geeks forGeeks"
 
# printing original string
print("The original string is : " + test_str)
 
 
res = ContainSpace(test_str,0)
# printing result
print("Does string contain spaces ? " + str(res))
 
#This code is contributed by vinay Pinjala.


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

Time complexity: O(n)
Auxiliary Space: O(n)

Method #8: Using the split() method
 

Python3




#Python3 code to demonstrate working of
#Check for spaces in string
#Using split() method
 
test_str = "Geeks forGeeks"
#Check for spaces
res = False
if len(test_str.split()) > 1:
  res = True
 
#printing result
print("Does string contain spaces ? " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

Does string contain spaces ? True

Time complexity: O(n)
Auxiliary Space: O(n), as it splits the string into a list of words.

Method #9:Using regex.findall() method

Python3




# 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.findall(r'[ ]+', test_str))
 
# printing result
print("Does string contain spaces ? " + str(res))


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

Time complexity: O(n)
Auxiliary Space: O(n)

Method #10:Using the any() function

The any() function is a built-in function in Python that takes an object and returns True if at least one element of the object is truthy, or False if all elements are falsy.

Python3




# Python3 code to demonstrate working of
# Check for spaces in string
 
# initializing string
test_str = "Geeks forGeeks"
 
# printing original string
print("The original string is : " + test_str)
 
# Using any() function
# Check for spaces
if any(c==' ' for c in test_str):
    res=True
else:
    res=False
 
# printing result
print("Does string contain spaces ? " + str(res))


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

Time complexity: O(n) iterates over the data structure
Auxiliary Space: O(1) does not takes any space.

Method #11:Using a while loop

Iterating over the string test_str checking each character if it equals to ‘ ‘ then storing the result TRUE and break from the loop else returning FALSE.

Python3




# Initializing string
test_string = "Geeks forGeeks"
  
# Printing original string
print("The original string is : " + test_string)
  
# Using a while loop to iterate over the string
res = False
i = 0
while i < len(test_string):
    if test_string[i] == " ":
        res = True
        break
    i += 1
  
print("Does string contain spaces ? " + str(res))


Output

The original string is : Geeks forGeeks
Does string contain spaces ? True

Time Complexity: O(N) as we are iterating over the string.

Auxiliary Space: O(1) as no extra memory is used.

Method #12: Using reduce():

Algorithm:

  1. Import the reduce() function from the functools module.
  2. Initialize a test string test_str.
  3. Use reduce() function to iterate over each character in test_str and check if it is a space character. The lambda function inside reduce() returns True if x is already True or if y is a space character. Otherwise, it returns False.
  4. The initial value of x in reduce() is False.
  5. The result is stored in res.
  6. Print whether the string contains spaces based on the value of res.

Python3




from functools import reduce
 
# initializing string
test_str = "Geeks forGeeks"
# printing original string
print("The original string is : " + test_str)
  
# Using reduce() method
# Check for spaces
res = reduce(lambda x, y: x or y == " ", test_str, False)
 
# printing result
print("Does string contain spaces? " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original string is : Geeks forGeeks
Does string contain spaces? True

Time Complexity: The reduce() method runs in linear time complexity O(n), where n is the length of the input string test_str. This is because reduce() applies the lambda function to each character in test_str one by one. Therefore, the time complexity of this code is O(n).

Space Complexity: The space complexity of this code is O(1). This is because the input string test_str is the only variable that requires memory space, and its size is independent of the input size. The reduce() method does not create a new list, so it doesn’t require additional memory space. Therefore, the space complexity of this code is constant, or O(1).

RELATED ARTICLES

Most Popular

Recent Comments