Skip to main content

How to count the number of words in a string in Python

How to count the number of words in a string in Python.

Here's a step-by-step tutorial on how to count the number of words in a string using Python:

Step 1: Define the string

First, you need to define the string for which you want to count the number of words. For example, let's say we have the following string:

string = "Hello, how are you today?"

Step 2: Use the split() function

Next, you can use the split() function to split the string into a list of words. By default, the split() function splits the string at each whitespace character (space, tab, or newline) and returns a list of the words. Here's an example:

words = string.split()

Step 3: Count the number of words

Once you have the list of words, you can simply count the number of elements in the list using the len() function. This will give you the total number of words in the string. Here's the code:

num_words = len(words)

Step 4: Print the result

Finally, you can print the number of words in the string using the print() function. Here's the code:

print("The number of words in the string is:", num_words)

Putting it all together, here's the complete code:

string = "Hello, how are you today?"
words = string.split()
num_words = len(words)
print("The number of words in the string is:", num_words)

This will output:

The number of words in the string is: 5

You can use this approach to count the number of words in any string in Python.