Python Count the Number of Words in a String

Document 对象参考手册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 calculating the length of the list. Below is a simple example code.

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 explanation:

  1. count_wordsThe function accepts a stringtextas a parameter.
  2. text.split()Split the string into a list of words by spaces. By default,split()the method uses any whitespace character (including spaces, newlines, etc.) as the delimiter.
  3. len(words)Return the length of the word list, i.e., the number of words.
  4. Example stringtextcontains 6 words.
  5. printThe function outputs the number of words.

Output result:

The number of words in the text is: 6

Document 对象参考手册Python3 Examples

Other Extensions