【发布时间】:2021-06-10 14:15:19
【问题描述】:
# 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))
我在 geeksforgeeks 中找到了这段代码,但我无法理解它,在使用 sum() 的行中,他们正在使用列表理解,所以我们必须使用方括号 ([ ]),但他们没有使用它,并且[not chr.isspace() for chr in test_str] 行返回一个 true 和 false 列表,但是输出如何给出正确的字符串长度值而不包含空格
【问题讨论】:
-
你不需要在字符串周围加上
str(…),它没用。 -
这是generator expression,不是列表理解