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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 14 views 0 copies

Python code

29 lines
Python 3.9+
def 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

stdout
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

  1. Use `re.findall(r'\w+', text)` from the `re` module to count words ignoring punctuation
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.