String helpers in Python: stats, reverse, and remove vowels
Three beginner-friendly Python functions compute text statistics, reverse word order, and strip vowels from a string.
Python code
29 linesdef text_stats(text: str) -> dict:
"""Return basic statistics for a given text string."""
words = text.split()
return {
"characters": len(text),
"words": len(words),
"sentences": text.count(".") + text.count("!") + text.count("?"),
"uppercase": sum(1 for c in text if c.isupper()),
"lowercase": sum(1 for c in text if c.islower()),
}
def reverse_words(text: str) -> str:
"""Reverse the order of words in a sentence."""
return " ".join(reversed(text.split()))
def remove_vowels(text: str) -> str:
"""Strip all vowels (a, e, i, o, u) from the text."""
vowels = "aeiouAEIOU"
return "".join(c for c in text if c not in vowels)
if __name__ == "__main__":
sample = "Hello world! Python is fun."
print("Original:", sample)
print("Stats:", text_stats(sample))
print("Reversed words:", reverse_words(sample))
print("Without vowels:", remove_vowels(sample))
Output
Original: Hello world! Python is fun.
Stats: {'characters': 27, 'words': 5, 'sentences': 2, 'uppercase': 2, 'lowercase': 21}
Reversed words: fun. is Python world! Hello
Without vowels: Hll wrld! Pythn s fn.
How it works
The text_stats function uses split() to count words (whitespace-separated tokens) and generator expressions with sum() to count uppercase and lowercase characters. reverse_words splits the string into a list, reverses it with reversed(), then joins back with a space. remove_vowels filters characters using a set-like membership check against a string of vowels, keeping only non-vowels. These helpers rely only on built-in string methods and standard idioms, making them easy to read and adapt.
Common mistakes
- Counting sentences by periods only, missing exclamation and question marks
- Assuming `text.split()` splits on punctuation as well as whitespace
- Forgetting that `reversed()` returns an iterator, not a list
- Checking vowels case-sensitively without including uppercase vowels
Variations
- Use `re.findall(r'\w+', text)` from the `re` module to count words ignoring punctuation
- Remove vowels with a translation table: `text.translate(str.maketrans('', '', 'aeiouAEIOU'))`
Real-world use cases
- Quick analysis of user-generated content to show character/word counts in a dashboard.
- Preprocessing text for a search index by removing vowels to normalize keywords.
- Building a simple word-reversal feature in a text editor or mobile app.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.