【问题标题】:Calculate spaces in a string [closed]计算字符串中的空格[关闭]
【发布时间】:2020-10-19 08:39:57
【问题描述】:

当我在网上看到这段代码时,我试图弄清楚如何计算字符串中的空格数。谁能解释一下?

text = input("Enter Text: ")

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

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

【问题讨论】:

  • 计算字符串中的空格。你到底有什么不清楚的地方?
  • 具体哪一部分不清楚?这几乎是用英语写的...cs 的计数与text 相加,它们是空格。是不是 .isspace() 让你感到困惑?
  • @BarbarosÖzhan get_string 来自 cs50 库。没有问题。
  • @Chase 除了需要安装...
  • @Chase 好吧,我同意你所说的话背后的常识,只是问题不清楚,我们只能假设 OP 实际上在问什么。 ..(究竟为什么这个问题现在已经结束了......)

标签: python isspace


【解决方案1】:

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

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

然后您执行sum,因为它表明它会将 True`s(1s) 和 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, False, False, False, True, False, False, False, False, False, True, False, False, False, False, True, False, False, True, False, False, False, False, False, False, False, False, False, False, False, False, False]
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4

【讨论】:

  • 它的基本意思是“在逐个字符地通过文本迭代时将作为空格的字符求和?
猜你喜欢
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多