Python Count the Number of Words in a String
In Python, we can get the number of words in a string by splitting the string into a list of words and then computing the length of the list. Here is a simple example.
Example
def
count_words
(
text
)
:
words
=
text.
split
(
)
return
len
(
words
)
Example string
text
=
"Hello world, this is a test."
word_count
=
count_words
(
text
)
(
f
"The number of words in the text is: {word_count}"
)
Code analysis:
count_wordsThe function takes a stringtextas its argument.text.split()Split the string into a list of words by spaces. By default, thesplit()method uses any whitespace character (including spaces, newlines, etc.) as the separator.len(words)Return the length of the word list, that is, the number of words.- Example string
textcontains 6 words. printfunction prints the number of words.
Output result:
The number of words in the text is: 6
Python3 Examples