Exercise39

Write a Python program that counts the number of words on a string text

Solution

Here’s a simple Python program that counts the number of words in a given string:

def count_words(text):
    """
    This function takes a string as input and returns the number of words in it.
    """
    words = text.split()
    return len(words)

# Here's an example of how to use the count_words function:
text = "This is an example sentence with nine words."
num_words = count_words(text)
print("Number of words:", num_words)
# output: Number of words: 9





This program:

  1. defines a function called count_words: that takes a single argument text.
  2. The split() method: is called on the input string text, which separates the string into a list of words using whitespace as a separator.
  3. The number of words: in the list is then returned using the len() function.

Note that this program assumes that words are separated by whitespace characters, such as spaces or tabs. If the input text contains other types of separators, such as punctuation marks or line breaks, you may need to modify the program to handle them properly.

 

Younes Derfoufi
my-courses.net

One thought on “Solution Exercise39: computing the number of word in given string text”

Leave a Reply