Master Python string manipulation by splitting text into words using the split() method to count total words.
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
Create a function count_words(txt) that takes a string of text and returns the total word count.
Text analysis, document search indexing, and social media post validation rely on calculating word counts.
Use the string .split() method to split text by spaces into a list of words, then measure length with len():
def count_words(txt):
words = txt.split()
return len(words)
# Testing our function
print(count_words("Just an example here")) # Output: 4
print(count_words("Is this easy?")) # Output: 3
print(count_words("Hello World")) # Output: 2
Calling .split() without arguments automatically handles multiple consecutive spaces, tabs, and newlines cleanly without creating empty string items.
txt.split(" "): Calling txt.split(" ") fails when multiple spaces exist between words! Always call txt.split() without arguments for general word tokenization.Use txt.split() and len() for word counts. Next, let's find the minimum and maximum numbers in a list!