Python – Avoid Spaces in string length

• Difficulty Level : Easy
• Last Updated : 05 Sep, 2020

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

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 result print("The Characters Frequency avoiding spaces : " + str(res))
Output
The original string is : geeksforgeeks 33 is   best
The Characters Frequency avoiding spaces : 21

My Personal Notes arrow_drop_up