Write a Python program that counts the number of words on a string text
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
- defines a function called count_words: that takes a single argument text.
- The split() method: is called on the input string text, which separates the string into a list of words using whitespace as a separator.
- 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.