How to Convert snake_case to Title Case in Python
Convert snake_case strings to title case by splitting on underscores, capitalizing each word, and joining them with spaces.
Python code
8 linesdef to_title_case(snake_str):
words = snake_str.split("_")
return " ".join(word.capitalize() for word in words)
if __name__ == "__main__":
examples = ["hello_world", "convert_snake_case", "already_title_case", "multiple__under_scores"]
for example in examples:
print(f"{example!r:35} -> {to_title_case(example)!r}")
Output
'hello_world' -> 'Hello World'
'convert_snake_case' -> 'Convert Snake Case'
'already_title_case' -> 'Already Title Case'
'multiple__under_scores' -> 'Multiple Under Scores'
How it works
The split("_") method breaks the snake_case string into a list of words at every underscore. Each word is passed to capitalize(), which uppercases the first character and lowercases the rest. The join method then assembles the words with a single space between them. The f-string with !r in the print call adds quotes around the output for clear visual formatting. Note that consecutive underscores produce empty strings, which remain as extra spaces when joined.
Common mistakes
- Using `.title()` which also capitalizes after apostrophes and can produce unexpected results
- Forgetting that input might be empty or contain leading/trailing underscores
- Assuming underscores are the only separator (e.g., hyphens or spaces won't work)
Variations
- Use `string.capwords(snake_str.replace('_', ' '), ' ')` from the `string` module for a similar result
- Convert to CamelCase instead by chaining `.title().replace(' ', '')` for a different output style
Real-world use cases
- Converting database column names (e.g., `user_first_name`) into human-readable labels for admin panels.
- Formatting API response keys from snake_case to title case for display in web dashboards.
- Building readable error messages from internal function or variable names in logging systems.
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.