Text Processor Functions for Beginners in Python

Demonstrates simple text-processing utilities: word counting, word reversal, whitespace normalization, and lowercase conversion using basic string methods.

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

Python code

23 lines
Python 3.9+
def count_words(text):
    """Return the number of words in a string."""
    return len(text.split())

def reverse_words(text):
    """Return the text with words in reverse order."""
    return ' '.join(text.split()[::-1])

def remove_extra_spaces(text):
    """Return text with extra whitespace collapsed to a single space."""
    return ' '.join(text.split())

def to_lower(text):
    """Return text converted to lowercase."""
    return text.lower()

if __name__ == "__main__":
    sample = "  Hello   Python  World!  "
    print("Original:", repr(sample))
    print("Word count:", count_words(sample))
    print("Reversed words:", reverse_words(sample))
    print("No extra spaces:", repr(remove_extra_spaces(sample)))
    print("Lowercase:", to_lower(sample))

Output

stdout
Original: '  Hello   Python  World!  '
Word count: 3
Reversed words: World! Python Hello
No extra spaces: 'Hello Python World!'
Lowercase:   hello   python  world!

How it works

The split() method without arguments splits on any whitespace and removes leading/trailing spaces, which powers both word counting and space collapsing. Reversing uses slicing with [::-1] on the list of words. These functions rely only on Python's built-in string methods, making them easy to read and modify. The if __name__ == "__main__" guard ensures the demo runs only when the script is executed directly, not when imported.

Common mistakes

  • Using `text.split(' ')` which fails on tabs or multiple spaces.
  • Forgetting that `split()` removes all extra whitespace, so `remove_extra_spaces` also trims edges.
  • Assuming `reverse_words` reverses characters instead of word order.

Variations

  1. Use `re.sub(r'\s+', ' ', text.strip())` for whitespace normalization.
  2. For preserving line breaks, use `splitlines()` before processing.

Real-world use cases

  • Counting words in user-generated content to power analytics dashboards.
  • Normalizing messy input fields before storing in a database.
  • Preparing text for NLP pipelines by reversing word order as a data augmentation step.

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.