How to Format Text in Python

A beginner-friendly helper that cleans and changes the case of a string, with options for title, upper, lower, and capitalize.

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

Python code

36 lines
Python 3.9+
def format_text(text, case="title", strip_whitespace=True, remove_extra_spaces=True):
    """
    Formats a string based on common beginner needs.
    
    Args:
        text: Input string to format
        case: "title", "upper", "lower", or "capitalize"
        strip_whitespace: Remove leading/trailing whitespace
        remove_extra_spaces: Collapse multiple spaces into one
    
    Returns:
        Formatted string
    """
    result = text
    if strip_whitespace:
        result = result.strip()
    if remove_extra_spaces:
        result = " ".join(result.split())
    if case == "title":
        result = result.title()
    elif case == "upper":
        result = result.upper()
    elif case == "lower":
        result = result.lower()
    elif case == "capitalize":
        result = result.capitalize()
    return result


if __name__ == "__main__":
    sample = "   hello   WORLD,   this IS a test   "
    print("Original:  ", repr(sample))
    print("Title:     ", format_text(sample, case="title"))
    print("Upper:     ", format_text(sample, case="upper"))
    print("Lower:     ", format_text(sample, case="lower"))
    print("Capitalize:", format_text(sample, case="capitalize"))

Output

stdout
Original:   '   hello   WORLD,   this IS a test   '
Title:      Hello World, This Is A Test
Upper:      HELLO WORLD, THIS IS A TEST
Lower:      hello world, this is a test
Capitalize: Hello world, this is a test

How it works

The helper starts by optionally stripping leading and trailing whitespace with strip(). Then " ".join(result.split()) collapses all runs of whitespace (including tabs and newlines) into a single space, normalizing the text. Next, the case transformation is applied using built-in string methods: title(), upper(), lower(), or capitalize(). Each transformation is simple and safe because it operates on a new string without mutating the original. The default is case="title", so calling format_text with just a string gives a clean title-cased result.

Common mistakes

  • Forgetting that `title()` uppercases every word, including articles like 'the' or 'a'.
  • Using `capitalize()` when you meant `title()` — it only uppercases the first character of the whole string.
  • Assuming `strip()` removes spaces between words; it only removes leading and trailing whitespace.
  • Not handling empty strings — the function returns an empty string, which is often unexpected but harmless.

Variations

  1. Use `casefold()` instead of `lower()` for aggressive Unicode-aware lowercasing.
  2. Use `re.sub(r'\s+', ' ', result).strip()` for regex-based whitespace normalization.

Real-world use cases

  • Cleaning user input before storing in a database, such as normalizing names or addresses.
  • Formatting product titles for consistent display across an e-commerce site.
  • Preparing text for analysis, like converting to lowercase or title case before tokenization.

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.