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.
Python code
36 linesdef 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
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
- Use `casefold()` instead of `lower()` for aggressive Unicode-aware lowercasing.
- 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
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.