1 回答

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊
isspace()如果字符串中的所有字符都是空格,則該方法返回 True,否則返回 False。
當(dāng)您c.isspace() for c in text逐個(gè)字符執(zhí)行此操作時(shí),如果它是空格,則返回 True(1),否則返回 False(0)
然后sum按照提示操作,將 True(1)和 False(0)相加。
您可以添加更多的打印語(yǔ)句以獲得更深入的理解。
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
添加回答
舉報(bào)