Python – 避免字符串长度中的空格
给定一个字符串,计算除空格之外的所有字符。
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.
方法#1:使用 isspace() + sum()
在此,我们使用 isspace() 和 not 运算符检查每个字符是否等于不等于 space(), sum() 用于检查频率。
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))
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))
输出
The original string is : geeksforgeeks 33 is best
The Characters Frequency avoiding spaces : 21
方法#2:使用 sum() + len() + map() + split()
在此,我们对空格进行拆分并提取没有空格的单词,然后使用 len() 计算长度(),使用 map() 扩展到每个单词,使用 sum() 计算的所有长度的总和是最终结果。
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))
输出
The original string is : geeksforgeeks 33 is best
The Characters Frequency avoiding spaces : 21