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 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}")
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:
count_wordsThe function accepts a stringtextas a parameter.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.len(words)Return the length of the word list, i.e., the number of words.- Example string
textcontains 6 words. printThe function outputs the number of words.
Output result:
The number of words in the text is: 6Other Extensions
Python3 Examples