Sling Academy
Home/Python/Python: 4 Ways to Count Words in a String

Python: 4 Ways to Count Words in a String

Last updated: May 25, 2023

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 pattern r'\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!

Next Article: Working with the str.replace() method in Python

Previous Article: Python: Capitalize the First Letter of each Word in a String

Series: Working with Strings in Python

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots