Introduction
Counting the number of words in a string is a common task in text processing. A word is typically defined as a sequence of characters separated by spaces. This tutorial will guide you through creating a Python program that counts the number of words in a given string.
Example:
-
Input:
hello world
-
Output:
Number of words: 2
-
Input:
Python programming is fun
-
Output:
Number of words: 4
Problem Statement
Create a Python program that:
- Takes a string as input.
- Counts the number of words in the string.
- Displays the total count of words.
Solution Steps
- Take Input from the User: Use the
input()
function to get a string from the user. - Split the String into Words: Use the
split()
method to break the string into a list of words. - Count the Number of Words: Use the
len()
function to count the number of elements in the list. - Display the Word Count: Use the
print()
function to display the total count of words.
Python Program
# Python Program to Count the Number of Words in a String
# Author: https://www.rameshfadatare.com/
# Step 1: Take input from the user
input_string = input("Enter a string: ")
# Step 2: Split the string into words
words = input_string.split()
# Step 3: Count the number of words
word_count = len(words)
# Step 4: Display the word count
print(f"Number of words: {word_count}")
Explanation
Step 1: Take Input from the User
- The
input()
function prompts the user to enter a string. The input is stored in the variableinput_string
.
Step 2: Split the String into Words
- The
split()
method is used to break the string into a list of words, where each word is a sequence of characters separated by spaces.
Step 3: Count the Number of Words
- The
len()
function is used to count the number of elements in the list, which represents the number of words in the string.
Step 4: Display the Word Count
- The
print()
function is used to display the total count of words in the string.
Output Example
Example 1:
Enter a string: hello world
Number of words: 2
Example 2:
Enter a string: Python programming is fun
Number of words: 4
Example 3:
Enter a string: This is a test string
Number of words: 5
Conclusion
This Python program demonstrates how to count the number of words in a string by splitting the string into a list of words and then counting the elements in that list. It’s a straightforward example that helps beginners understand string manipulation, lists, and basic functions in Python.