pythonisspace

Calculate spaces in a string


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?


Solution

  • The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.

    When you do c.isspace() for c in text while going character by character it returns True(1) if it is a whitespace, otherwise False(0)

    Then you do sum as it suggests it adds up True`s(1s) and False(0s).

    You can add more print statements to have deeper understanding.

    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