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.

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

Python code

8 lines
Python 3.9+
def 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

stdout
'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

  1. Use `string.capwords(snake_str.replace('_', ' '), ' ')` from the `string` module for a similar result
  2. 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

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.