计算字符串中的空格

问题描述

当我在线遇到此代码时,我试图弄清楚如何计算字符串中的空格数。有人可以解释一下吗?

text = input("Enter Text: ")

spaces = sum(c.isspace() for c in text)

我遇到的问题是语句“ sum(c.isspace()for text in text)”,“ c”是否表示字符,并且可以是其他字符吗?

解决方法

如果字符串中的所有字符都是空格,则isspace()方法将返回True,否则返回False。

当您逐个字符移动c.isspace() for c in text时,如果它是空格,则返回True(1),否则返回False(0)

然后您执行sum,因为它建议将True和False相加(0s)。

您可以添加更多打印语句以加深了解。

text = input("Enter Text: ")

spaces = sum(c.isspace() for c in text)
print([c.isspace() for c in text])
print([int(c.isspace()) for c in text])
print(spaces)
Enter Text: Hello World this is StackOverflow
[False,False,True,False]
[0,1,0]
4