Python – Avoid Spaces in string length
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 stringtest_str = 'geeksforgeeks 33 is best'# printing original stringprint("The original string is : " + str(test_str))# isspace() checks for space# sum checks countres = sum(not chr.isspace() for chr in test_str) # printing resultprint("The Characters Frequency avoiding spaces : " + str(res)) |
The original string is : geeksforgeeks 33 is best The Characters Frequency avoiding spaces : 21
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 stringtest_str = 'geeksforgeeks 33 is best'# printing original stringprint("The original string is : " + str(test_str))# len() finds individual word Frequency# sum() extracts final Frequencyres = sum(map(len, test_str.split())) # printing resultprint("The Characters Frequency avoiding spaces : " + str(res)) |
The original string is : geeksforgeeks 33 is best The Characters Frequency avoiding spaces : 21
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 stringtest_str = 'geeksforgeeks 33 is best'# printing original stringprint("The original string is : " + str(test_str))test_str=test_str.replace(' ','')res=len(test_str) # printing resultprint("The Characters Frequency avoiding spaces : " + str(res)) |
The original string is : geeksforgeeks 33 is best The Characters Frequency avoiding spaces : 21


