The number of words. Given a string consisting of words separated by spaces, determine how many words it contains. Use the count
method to solve this problem.
|
s = input() word_count = s.count(' ') + 1 print(word_count) |
Explanation of the Code
- Reading Input:
- The
input()
function reads a line of text from the user and stores it in the variable s
.
- Counting Words:
word_count = s.count(' ') + 1
- The
count
method counts the number of spaces in the string.
- Adding 1 to the count of spaces gives the number of words, since the number of words is always one more than the number of spaces in a properly spaced sentence.
- Printing the Word Count:
- The
print()
function outputs the value of word_count
.