How to Format Text in Python (Beginner's Guide)
This beginner-friendly Python script demonstrates text formatting basics: stripping whitespace, converting to title case, replacing substrings, splitting into words, and generating a snippet.
Python code
14 linestext = " hello world, welcome to python skillset! "
cleaned = text.strip()
title_cased = cleaned.title()
replaced = title_cased.replace("Python", "PYTHON")
words = replaced.split()
word_count = len(words)
first_three = " ".join(words[:3])
snippet = first_three + "..."
print("Original:", repr(text))
print("Stripped:", cleaned)
print("Title case:", title_cased)
print("Replaced:", replaced)
print("Word count:", word_count)
print("Snippet:", snippet)
Output
Original: ' hello world, welcome to python skillset! '
Stripped: hello world, welcome to python skillset!
Title case: Hello World, Welcome To Python Skillset!
Replaced: Hello World, Welcome To PYTHON Skillset!
Word count: 6
Snippet: Hello World, Welcome...
How it works
The strip() method removes leading and trailing whitespace from the string, making it clean for further processing. The title() method converts the first character of each word to uppercase and the rest to lowercase. The replace() method substitutes all occurrences of one substring with another. The split() method divides the string into a list of words using spaces as delimiters. Finally, join() concatenates a slice of that list back into a string, which is a common pattern for generating previews or summaries.
Common mistakes
- Forgetting that `strip()` only removes whitespace from the ends, not inside the string
- Assuming `split()` splits on commas or other punctuation unless you specify the separator
- Using `replace()` without checking if the substring exists, which can lead to unexpected results
- Building snippets with `+` instead of using `join()` to avoid extra spaces or errors
Variations
- Use `re.sub()` from the `re` module for more complex pattern-based replacements.
- Extract the snippet with `' '.join(words[:3]) + '...'` — already shown, but you could also use a generator expression for larger texts.
Real-world use cases
- Cleaning user input from web forms before storing or processing it.
- Generating title-case labels or headers in reports and dashboards.
- Creating preview snippets for blog posts or search results from long texts.
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.