How to Capitalize First Letter of Each Word in Python
Capitalizes the first letter of every word in a string using the built-in title() method.
Python code
7 linesdef capitalize_words(text):
return text.title()
if __name__ == "__main__":
sample = "hello world from python"
result = capitalize_words(sample)
print(result)
Output
Hello World From Python
How it works
The title() method returns a copy of the original string where the first character of each word is uppercase and all other letters are lowercase. It splits the string on whitespace, applies the transformation, and preserves the order. This works without any external libraries, making it a quick solution for simple capitalization tasks. Note that title() also lowercases the rest of each word, which may affect mixed-case input.
Common mistakes
- Using `capitalize()` which only uppercases the first character of the entire string, not each word
- Assuming `title()` preserves the original casing of the rest of the word — it lowercases everything else
- Forgetting that `title()` treats apostrophes as word boundaries, e.g., 'don't' becomes 'Don'T'
- Using `upper()` which makes all characters uppercase instead of just the first letter
Variations
- Use a list comprehension with `.capitalize()`: `' '.join(word.capitalize() for word in text.split())`
Real-world use cases
- Formatting user input names (e.g., converting 'john doe' to 'John Doe') before storing in a database.
- Normalizing product titles in an e-commerce catalog for consistent display.
- Preparing data for reports or dashboards where word capitalization improves readability.
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.