Python Program to Count the Number of Words in a String

1. Introduction

Counting the number of words in a string is a common task in text analysis and natural language processing. Python provides several ways to accomplish this, and one of the most straightforward methods is by splitting the string into words and counting the elements in the resulting list.

2. Program Steps

1. Define the string to be analyzed.

2. Use the split method to divide the string into a list of words.

3. Count the number of elements in the list.

4. Print the word count.

3. Code Program

# Define the string
input_string = "Hello, welcome to the world of Python."

# Split the string into words
words = input_string.split()

# Count the number of words in the list
word_count = len(words)

# Print the word count
print(f"The number of words in the string is: {word_count}")

Output:

The number of words in the string is: 7

Explanation:

1. input_string is a string variable that holds the sentence to be analyzed.

2. split() is a string method that breaks the string into a list where each word is a list item. By default, it uses any whitespace as a delimiter.

3. words is the list created by split(), containing each word as an individual element.

4. word_count is obtained by using the len() function, which counts the number of items in the list words.

5. The final print statement uses an f-string to output the number of words, which in this case is 7.

Comments