-2

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?

  • 2
    It counts the spaces in a string. What exactly is unclear to you about it? – mkrieger1 Oct 19 '20 at 08:41
  • What part exactly is not clear? This is almost written English... *sum the count of `c`s from `text` which are spaces*. Is it the [`.isspace()`](https://docs.python.org/3/library/stdtypes.html#str.isspace) that confuses you? – Tomerikoo Oct 19 '20 at 08:42
  • 1
    @BarbarosÖzhan `get_string` is from the cs50 library. There's no problem with that. – Chase Oct 19 '20 at 08:44
  • @Chase except that it needs to be installed... – Tomerikoo Oct 19 '20 at 08:44
  • @Tomerikoo that hardly matters in this specific case. OP is probably following the cs50 course. They probably aren't asking for how to take input, that should be explained by cs50 eventually – Chase Oct 19 '20 at 08:46
  • 1
    @Chase Well I'll agree with the common sense behind what you said, except that the question is not clear and we can only **assume** what OP is actually asking about... (Exactly why the question is now closed...) – Tomerikoo Oct 19 '20 at 08:50

1 Answers1

3

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
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22