0

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 = get_string("Enter Text: ")

spaces = sum(c.isspace() for c in text)

0

https://www.programiz.com/c-programming/library-function/ctype.h/isspace

isspace() checks if a character is a white-space or not (blanks, newlines, tabs etc.) first line of the code gets a text from the user (get_string() is a CS50 specific function not a standard one) next line counts the spaces ...it is the same thing as:

def spaces():
    sum = 0
    # iterate through all the characters in the text 
    for c in text:
        # check if the function is true for that character c
        if c.isspace():   
           sum += 1
    return sum

but instead of writing all this, you can also write in one line of code like that.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .