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.

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

Python code

14 lines
Python 3.9+
text = "  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

stdout
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

  1. Use `re.sub()` from the `re` module for more complex pattern-based replacements.
  2. 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

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.