This practical, example-based article will walk you through a couple of different ways to count the number of words in a given string in Python. Let’s get right in!
Using the split() method and the len() function
This approach contains two main steps:
- Use the
split()
method to turn the string into a list of words based on whitespace. - Use the
len()
function on the resulting list to get the count of words.
Example:
string = "Welcome to Sling Academy"
word_list = string.split()
word_count = len(word_list)
print(word_count)
Output:
4
Using regular expressions
In short, this is a three-step process:
- Import the
re
module. - Use the
re.findall()
function with the regular expression patternr'\b\w+\b'
to find all occurrences of word patterns in the string. - Use the
len()
function on the resulting list to get the count of words.
Here’s how we implement the steps above with code:
import re
string = "Are you the Wolf of Wall Street?"
word_list = re.findall(r'\b\w+\b', string)
word_count = len(word_list)
print(word_count)
Output:
7
Using the count() method and a space delimiter
The count()
method can be used to count the number of occurrences of a substring within a string. By counting the occurrences of the space delimiter (then adding 1), you can determine the number of words.
Example:
string = "Romance of the Three Kingdoms and Water Margin are two of the four great classical novels of Chinese literature."
word_count = string.count(" ") + 1
print(word_count)
Output:
19
Since the number of words is one more than the number of spaces, we add 1 to the count.
Using the split() method and a generator expression
As said in the first approach, the split()
method can be used to split the string into a list of words. By passing the resulting list to a generator expression and summing the boolean values of non-empty words, you can determine the number of words.
Example:
string = "Turtles are the fastest animals in the world" # Don't believe me
word_count = sum(bool(word) for word in string.split())
print(word_count)
Output:
8
If you know animals that run faster than turtles, please let me know by leaving a comment. I’ll be happy to hear from you. Happy coding & have a nice day!