How to Write a Normalize Function with Default Parameters in Python
Define a reusable normalize function with configurable default parameters for lowercase conversion, whitespace stripping, and punctuation removal.
Python code
16 linesdef normalize(text, lowercase=True, strip_whitespace=True, remove_punctuation=False):
"""Normalize a string based on configurable options."""
if lowercase:
text = text.lower()
if strip_whitespace:
text = text.strip()
if remove_punctuation:
text = ''.join(char for char in text if char.isalnum() or char.isspace())
return text
if __name__ == "__main__":
sample = " Hello, World! "
print(f"Default: {normalize(sample)!r}")
print(f"No lowercase: {normalize(sample, lowercase=False)!r}")
print(f"All options: {normalize(sample, lowercase=True, strip_whitespace=True, remove_punctuation=True)!r}")
Output
Default: 'hello, world!'
No lowercase: ' Hello, World! '
All options: 'hello world'
How it works
The normalize function uses default parameters to make each transformation optional. When lowercase=True, it converts all characters to lowercase with .lower(). strip_whitespace=True removes leading and trailing spaces via .strip(). The remove_punctuation flag filters characters with a generator expression, keeping only alphanumeric characters and whitespace using isalnum() and isspace(). Default parameters let callers override behavior per call without changing the function signature. The if __name__ == "__main__" guard runs the demo only when the script is executed directly, not when imported.
Common mistakes
- Forgetting that `.strip()` only removes leading/trailing whitespace, not internal spaces
- Expecting `remove_punctuation` to also remove whitespace or special characters like emojis
- Mutating the original string instead of returning a new one — note strings are immutable, so `text` is reassigned
Variations
- Use `functools.partial` to create a specialized version with preset options
- Add a `normalize_whitespace` option to collapse multiple internal spaces into one
Real-world use cases
- Cleaning user input in a web form before validating email or username fields.
- Normalizing search query text so matching is case-insensitive and whitespace-tolerant.
- Preprocessing OCR or scraped text before storing it in a database or passing it to an NLP model.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.