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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

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

stdout
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

  1. Use `functools.partial` to create a specialized version with preset options
  2. 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

Run this sample

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

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.