I was trying to figure out how to calculate the number of spaces in a string when I came across this code online. Can someone please explain it?
text = input("Enter Text: ")
spaces = sum(c.isspace() for c in text)
The issue im having is with the statement "sum(c.isspace() for c in text)", Does the "c" signify character and can it be something else?
The
isspace()method returns True if all the characters in a string are whitespaces, otherwise False.When you do
c.isspace() for c in textwhile going character by character it returns True(1) if it is a whitespace, otherwise False(0)Then you do
sumas it suggests it adds up True`s(1s) and False(0s).You can add more print statements to have deeper understanding.