Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Count the Number of Words in a String

Python Count the Number of Words in a String

Document Object Reference Manual Python3 Examples

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

)

print

(

f

"The number of words in the text is: {word_count}"

)

Code analysis:

  1. count_words The function takes a string text as its argument.
  2. 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.
  3. len(words) Return the length of the word list, that is, the number of words.
  4. Example string text contains 6 words.
  5. print function prints the number of words.

Output result:

The number of words in the text is: 6

Document Object Reference Manual Python3 Examples