为了账号安全,请及时绑定邮箱和手机立即绑定

计算字符串中的空格

计算字符串中的空格

慕斯王 2023-12-09 16:48:07
当我在网上看到这段代码时,我试图弄清楚如何计算字符串中的空格数。有人可以解释一下吗?text = input("Enter Text: ")spaces = sum(c.isspace() for c in text)我遇到的问题是语句“sum(c.isspace() for c in text)”,“c”是否表示字符,它可以是其他东西吗?
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

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


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


然后sum按照提示操作,将 True(1)和 False(0)相加。


您可以添加更多的打印语句以获得更深入的理解。


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


查看完整回答
反对 回复 2023-12-09
  • 1 回答
  • 0 关注
  • 38 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信