0
0
PythonHow-ToBeginner · 3 min read

How to Title Case a String in Python: Simple Guide

In Python, you can convert a string to title case using the str.title() method, which capitalizes the first letter of each word. Simply call your_string.title() to get the title-cased version of the string.
📐

Syntax

The str.title() method is called on a string to convert it to title case. It returns a new string where the first letter of each word is capitalized and the rest are lowercase.

  • your_string: The original string you want to convert.
  • your_string.title(): Returns the title-cased string.
python
title_cased_string = your_string.title()
💻

Example

This example shows how to use str.title() to convert a sentence to title case.

python
text = "welcome to the world of python programming"
title_cased = text.title()
print(title_cased)
Output
Welcome To The World Of Python Programming
⚠️

Common Pitfalls

One common mistake is expecting str.title() to handle apostrophes or acronyms correctly. For example, it will capitalize letters after apostrophes, which may not be desired.

Also, str.title() lowercases all other letters, so it may change acronyms like "NASA" to "Nasa".

python
text_wrong = "they're learning python's basics"
print(text_wrong.title())  # Output: They'Re Learning Python'S Basics

# Correct approach for apostrophes requires custom handling or libraries
Output
They'Re Learning Python'S Basics
📊

Quick Reference

Title Case Conversion in Python

MethodDescription
str.title()Capitalizes first letter of each word, lowercases others
MethodDescription
str.title()Capitalizes first letter of each word, lowercases others

Key Takeaways

Use str.title() to convert strings to title case easily in Python.
str.title() capitalizes the first letter of each word and lowercases the rest.
It may not handle apostrophes or acronyms correctly, so watch out for those cases.
For more complex title casing, consider custom functions or libraries.