Python Program to Count the Number of Words in a String

In this tutorial, we will discuss a Python program to count the number of words in a string.

Related: Python Program to Check if a String is a Palindrome

Program code to count the number of words in a string in Python

# Count Words in a String in Python
def count_words(string):
    words = string.split()
    return len(words)

input_string = input("Enter a string: ")
word_count = count_words(input_string)
print(f"Number of words: {word_count}")

Explanation

  1. Function Definition: The count_words function takes a string as input, splits it into words, and returns the number of words.
  2. Main Program: The program prompts the user to enter a string and then counts the number of words using the count_words function and prints the result.

Output

Python Program to Count the Number of Words in a String

  • When you run the above program, it will prompt you to enter a string.
  • After entering the string, it will count the number of words and print the result.

Conclusion

  • In this tutorial, we learned how to count the number of words in a string using a Python program.
  • Understanding this concept is essential for text analysis and enhancing your programming skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *