Open In App

Python – Avoid Spaces in string length

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a String, compute all the characters, except spaces.

Input : test_str = ‘geeksforgeeks 33 best’ 
Output : 19 
Explanation : Total characters are 19. 

Input : test_str = ‘geeksforgeeks best’ 
Output : 17 
Explanation : Total characters are 17 except spaces.

Method #1 : Using isspace() + sum()

In this, we check for each character to be equal not to space() using isspace() and not operator, sum() is used to check frequency.

Python3




# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using isspace() + sum()
 
# initializing string
test_str = 'geeksforgeeks 33 is   best'
 
# printing original string
print("The original string is : " + str(test_str))
 
# isspace() checks for space
# sum checks count
res = sum(not chr.isspace() for chr in test_str)
     
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))


Output

The original string is : geeksforgeeks 33 is   best
The Characters Frequency avoiding spaces : 21

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

Method #2 : Using sum() + len() + map() + split()

In this, we perform split on spaces and extract words without spaces, then the length() of is computed using len() extended to each word using map(), the summation of all lengths computed using sum() is final result.

Python3




# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
# Using sum() + len() + map() + split()
 
# initializing string
test_str = 'geeksforgeeks 33 is   best'
 
# printing original string
print("The original string is : " + str(test_str))
 
# len() finds individual word Frequency
# sum() extracts final Frequency
res = sum(map(len, test_str.split()))
     
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))


Output

The original string is : geeksforgeeks 33 is   best
The Characters Frequency avoiding spaces : 21

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

Method #3 : Using replace() method.
Using replace() we will replace the space in the string with an empty string and then find the length using len() method.

Python3




# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
 
 
# initializing string
test_str = 'geeksforgeeks 33 is best'
 
# printing original string
print("The original string is : " + str(test_str))
 
test_str=test_str.replace(' ','')
res=len(test_str)   
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))


Output

The original string is : geeksforgeeks 33 is best
The Characters Frequency avoiding spaces : 21

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

Method #4 : Using loop and maintaining count variable.

Approach:

  1. Initialize a count variable with 0.
  2. Iterate the string character by character using loop.
  3. If the character is an empty character with space (‘ ‘) then skip that iteration and don’t increase the count variable.
  4. Other than empty character in string, increase the count variable by 1 in each iteration.
  5. At the end of loop, print the count variable that shows string length avoiding spaces.

Python3




# Python3 code to demonstrate working of
# Avoid Spaces in Characters Frequency
 
 
# initializing string
test_str = 'geeksforgeeks 33 is   best'
 
# printing original string
print("The original string is : " , test_str)
 
# initializing count = 0
count = 0
 
# loop to iterate the string, character by character
for i in test_str:
    if i == ' ':
        continue
    count += 1
     
# printing result
print("The Characters Frequency avoiding spaces : " , count)
 
# This code is contributed by Pratik Gupta (guptapratik)


Output

The original string is :  geeksforgeeks 33 is   best
The Characters Frequency avoiding spaces :  21

Time Complexity: O(n)
Auxiliary Space: O(n), where n is total characters in string.

Method #5: Using a list comprehension and the join() function

Step-by-step approach:

  • Set a counter variable res to 0
  • For each character char in test_str, do the following:
    • If char is not a whitespace character, increment res by 1
  • Return res as the result

Python3




# initializing string
test_str = 'geeksforgeeks 33 is best'
 
# printing original string
print("The original string is : " + str(test_str))
 
# Using a list comprehension and the join() function
res = len(''.join([char for char in test_str if char != ' ']))
 
# printing result
print("The Characters Frequency avoiding spaces : " + str(res))


Output

The original string is : geeksforgeeks 33 is best
The Characters Frequency avoiding spaces : 21

Time complexity: O(n), where n is the length of the input string test_str. This is because the algorithm uses a list comprehension to iterate over each character in the string exactly once, and the join() function also iterates over each character in the resulting list exactly once.
Space complexity: O(n), where n is the length of the input string test_str. This is because the algorithm creates a list of non-whitespace characters in the input string, which can be up to the same size as the input string. However, this list is discarded after the join() function is called, so the total space used by the algorithm is still O(n).

Method #6:  Using a lambda function and the reduce() method

  • Import the functools module.
  • Create a lambda function called func that takes in two arguments x and y.
  • If the value of y is not a space, the lambda function returns x + 1.
  • If the value of y is a space, the lambda function returns x.
  • Use the reduce() function from functools module and apply the func lambda function to every element of the test_str string. Start with an initial value of 0.
  • Store the result of reduce() in the variable res.
  • Print the final result using the print() function. The result is the number of non-space characters in the original string.

Python3




import functools
 
# Initializing string
test_str = 'geeksforgeeks 33 is best'
 
# Printing original string
print("The original string is : " + str(test_str))
 
# Using lambda function and reduce method
func = lambda x, y: x + (1 if y != ' ' else 0)
res = functools.reduce(func, test_str, 0)
 
# Printing result
print("The Characters Frequency avoiding spaces : " + str(res))


Output

The original string is : geeksforgeeks 33 is best
The Characters Frequency avoiding spaces : 21

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



Similar Reads

Python code to move spaces to front of string in single traversal
Given a string that has set of words and spaces, write a program to move all spaces to front of string, by traversing the string only once. Examples: Input : str = "geeks for geeks" Output : str = " geeksforgeeks" Input : str = "move these spaces to beginning" Output : str = " movethesespacestobeginning" There were four space characters in input, a
5 min read
Python | String Split including spaces
The problems and at the same time applications of list splitting are quite common while working with python strings. The spaces usually tend to ignore in the use cases. But sometimes, we might not need to omit the spaces but include them in our programming output. Let's discuss certain ways in which this problem can be solved. Method #1: Using spli
4 min read
Python | Remove unwanted spaces from string
Sometimes, while working with strings, we may have situations in which we might have more than 1 spaces between intermediate words in strings that are mostly unwanted. This type of situation can occur in web development and often needs rectification. Let's discuss certain ways in which this task can be performed. Examples: Example 1: Input: GfG is
4 min read
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 b
8 min read
Python - Ways to remove multiple empty spaces from string List
Sometimes, while working with Python strings, we have a problem in which we need to perform the removal of empty spaces in Strings. The problem of filtering a single space is easier. But sometimes we are unaware of the number of spaces. This has applications in many domains. Let's discuss certain ways in which this task can be performed. Method #1
6 min read
Python | Test if String contains Alphabets and Spaces
Sometimes, while testing of credibility of string being a part of containing just alphabets, an exception of spaces has to be mentioned explicitly and becomes a problem. This can occur in domains that deal with data. Lets discuss certain ways in which this task can be performed. Method #1 : Using all() + isspace() + isalpha() This is one of the way
5 min read
Python program to count the number of spaces in string
Given a string, the task is to write a Python program to count the number of spaces in the string. Examples: Input: "my name is geeks for geeks" Output: number of spaces = 5 Input: "geeksforgeeks" Output: number of spaces=0 Approach: Input string from the userInitialize count variable with zeroRun a for loop i from 0 till the length of the stringIn
5 min read
Fill a Python String with Spaces
This article will show you to fill out a python string with spaces to the left, right, and around a string in Python. Let's suppose we have a string GeeksforGeeks, and we want to fill N number of spaces on left, right, and around the string. Note that in the case of space around the string if N is odd then the extra space is added to the right of t
4 min read
Python | Remove spaces from a string
Removing spaces from a string involves eliminating any whitespace characters within the string. This can be accomplished using various methods in Python like replace(), translate(), istrip(), etc. By removing spaces from a string, you can manipulate and process the string more easily, perform comparisons, or use it in various other operations. In t
5 min read
Python string length | len() function to find string length
The string len() function returns the length of the string. In this article, we will see how to find the length of a string using the string len() method. Example: C/C++ Code string = "Geeksforgeeks" print(len(string)) Output13String len() Syntax len(string) Parameter String: string of which you want to find the length. Return: It returns
3 min read
Practice Tags :