Hit enter after type your search item

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


Result:

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:


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:


Result:

Number of Words =  13

Note: It’s drawback is, it also counts quotes or other special characters separately.

This div height required for enabling the sticky sidebar