Use text.title() for standard title-casing across whitespace and punctuation, or string.capwords(text) (from the built-in string module) when you want apostrophes inside contractions/possessives ("it's", "o'connor") kept lowercase and consecutive whitespace collapsed into single spaces—since str.title() splits at every non-letter character and turns "it's" into "It'S".
Basic Example
import string
sentence = "hello world! it's python 3.12"
# 1. Standard built-in `.title()` (capitalizes after any non-letter character):
print(sentence.title())
# Output: Hello World! It'S Python 3.12
# 2. Recommended for English prose with apostrophes (`string.capwords`):
print(string.capwords(sentence))
# Output: Hello World! It's Python 3.12
# 3. Preserve original spacing while capitalizing only whitespace-separated tokens:
custom = " it's alice's book "
print(" ".join(word.capitalize() for word in custom.split(" ")))
# Output: It's Alice's Book
Key Details & Edge Cases
- The apostrophe & hyphen trap in
str.title()("It'S"vs."It's"):str.title()treats any non-cased character (including',-, and digits) as a word boundary, producing"Don'T","Rock'N'Roll", and"3Rd".string.capwords(s)splits solely on whitespace (s.split()), applies.capitalize()to each token, and rejoins with" ", cleanly producing"Don't","Rock'n'roll", and"3rd".
- Whitespace normalization side effect of
string.capwords(s):- Because
string.capwords(s)callss.split()with no arguments, it strips leading/trailing whitespace and collapses tabs, newlines, or multiple spaces into single spaces ("a b\nc"$\rightarrow$"A B C"). Use" ".join(w.capitalize() for w in s.split(" "))(or regexre.sub(r"\S+", lambda m: m.group(0).capitalize(), s)) when exact whitespace formatting must be preserved.
- Because
- Unicode case-mapping edge cases (
ß,İ, digraphs likedž):- Both
.title()and.capitalize()follow full Unicode case rules:"straße".title()becomes"Straße"(whereas.upper()turnsßinto"SS"), and Croatian titlecase digraphs like"dž"convert to"Dž"under.title()rather than"DŽ".
- Both
- Preserving existing acronyms (
"NASA","API","iPhone"):- Both
.title()and.capitalize()lowercase every character after index0("NASA mission".title()$\rightarrow$"Nasa Mission"). To capitalize only the first character of each word without lowercasing uppercase acronyms, usere.sub(r"\b[a-z]", lambda m: m.group(0).upper(), text)(note:\bwill still trigger after apostrophes unless guarded with(?<!')).
- Both
- Immutability of Python strings:
- Strings in Python are immutable—
text.title()returns a newstrand leavestextunchanged unless reassigned (text = text.title()).
- Strings in Python are immutable—
Comparison of Word-Capitalization Methods in Python
| Method | Handles Apostrophes ("it's" $\rightarrow$ "It's")? |
Preserves Original Whitespace (\n, multiple spaces)? |
Preserves Uppercase Acronyms ("API")? |
Best Used When |
|---|---|---|---|---|
string.capwords(s) (Recommended) |
Yes ("It's") |
No (collapses runs of whitespace to " ") |
No ("Api") |
Formatting names, titles, and English sentences containing contractions or possessives. |
s.title() |
No ("It'S") |
Yes | No ("Api") |
Quick zero-import formatting when strings lack apostrophes or require punctuation boundaries ("well-known" $\rightarrow$ "Well-Known"). |
re.sub(r"\S+", lambda m: m.group(0).capitalize(), s) |
Yes ("It's") |
Yes (keeps \n, tabs, and spaces intact) |
No ("Api") |
Multi-line text or formatted blocks where exact spacing and contractions must both stay intact. |
re.sub(r"(?<!')\b[a-z]", lambda m: m.group(0).upper(), s) |
Yes ("It's") |
Yes | Yes ("API") |
Headlines or technical titles containing acronyms (NASA, SQL, HTTP) that must remain uppercase. |
You must log in or register to comment.
