To count the words in an input in Python, you can use the following approach:
input_string = input("Enter a sentence: ")
word_list = input_string.split() # Split the input string into words
word_count = len(word_list) # Get the count of words
print("Word count:", word_count)
In this approach, we start by using the built-in input()
function to prompt the user for input. The input is stored in a string variable called input_string
. We then use the split()
method on the input_string
to split it into words, which returns a list of words. The split()
method splits the string by whitespace characters (spaces, tabs, and newlines) by default, which separates the input into individual words.
Next, we use the len()
function to get the count of words in the word_list
, which gives us the total number of words in the input. Finally, we print the word count using print()
.
+ There are no comments
Add yours