亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

計算字符串中的空格

計算字符串中的空格

慕斯王 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 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號