Python Programs to Get Count of Words in a String

How to get the total number of words in a String in Python?

In this tutorial, we will show you solutions to get the total number of words in a given string.

Program 1 – Using Split function with Len()

The first program uses split and len() methods.

The split() is used to break a given string by a delimiter. For example,

strmet.split(‘,’)

It returns a list of broken strings into a list.

You may learn about the Python split method.

By using this method, we will break the string that we want to get the count for.

We will pass the list created by split() method to the len() – that returns the length of the list.

Code:

#Source string to ge the count of words

my_str = "The way to get started is to quit talking and begin doing."
print ("Our source string = " + my_str)

#Split returns list
print (my_str.split())

# using split() with len
word_count = len(my_str.split())

print ("Number of Words = " + str(word_count))

Result:

Our source string = The way to get started is to quit talking and begin doing.

[‘The’, ‘way’, ‘to’, ‘get’, ‘started’, ‘is’, ‘to’, ‘quit’, ‘talking’, ‘and’, ‘begin’, ‘doing.’]

Number of Words = 12

Program 2: Using Split and for loop to count the words

In the following example, we used the split method to get the list of broken words from the given string.

Then we used a for loop to count the words in that list:

#Source string to ge the count of words

my_str = "Don't judge each day by the harvest you reap but by the seeds that you plant."

word_count = 0


for item in my_str.split():

  word_count += 1

# Count of words

print ("Number of Words = " , word_count)

Result:

Number of Words =  16

Program 3: Using regex and len() to get the total count

We will use:

  • findall()
  • pattern is r’\w+’. It will match the words in the string.
  • len() will get the count of words

Python code:

import re

#Source string to ge the count of words

my_str = "Never let the fear of striking out keep you from playing the game."


word_count = len(re.findall(r'\w+', my_str))

print ("Number of Words = " , word_count)

Result:

Number of Words =  13
Note: It’s drawback is, it also counts quotes or other special characters separately.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!