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.
Python code
23 linesdef 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
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
- Use `re.sub(r'\s+', ' ', text.strip())` for whitespace normalization.
- 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
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.