Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between str.capitalize() vs str.title()
In Python, strings are immutable sequences of characters that can be manipulated using various built-in methods. Two commonly used string methods are capitalize() and title(), which both modify the case of characters but work differently.
str.capitalize()
The capitalize() method converts only the first character of the entire string to uppercase and makes all remaining characters lowercase. It treats the entire string as a single unit, regardless of spaces or word boundaries.
Syntax
str_name.capitalize()
Here, str_name is the input string. The method takes no arguments and returns a new string.
Example
text = 'hello world python' print(text.capitalize()) # With mixed case mixed_text = 'hELLO wORLD' print(mixed_text.capitalize())
Hello world python Hello world
str.title()
The title() method capitalizes the first character of each word in the string and converts all remaining characters to lowercase. It identifies word boundaries and treats each word separately.
Syntax
str_name.title()
Here, str_name is the string to be modified. Like capitalize(), it takes no arguments.
Example
text = 'hello world python' print(text.title()) # With mixed case mixed_text = 'hELLO wORLD' print(mixed_text.title())
Hello World Python Hello World
Key Differences
name = "john doe"
sentence = "this is a SENTENCE."
print("capitalize():")
print(name.capitalize())
print(sentence.capitalize())
print("\ntitle():")
print(name.title())
print(sentence.title())
capitalize(): John doe This is a sentence. title(): John Doe This Is A Sentence.
Comparison
| Feature | str.capitalize() | str.title() |
|---|---|---|
| Scope | Entire string as one unit | Each word separately |
| First character | Only the very first character | First character of each word |
| Remaining characters | All lowercase | All lowercase within each word |
| Best for | Sentences, single thoughts | Titles, proper nouns |
Common Use Cases
# capitalize() for sentences
sentence = "python is a programming language."
print("Sentence:", sentence.capitalize())
# title() for names and titles
book_title = "the great gatsby"
person_name = "alice smith"
print("Book:", book_title.title())
print("Name:", person_name.title())
Sentence: Python is a programming language. Book: The Great Gatsby Name: Alice Smith
Conclusion
Use capitalize() when you need to format sentences or paragraphs with proper sentence case. Use title() when formatting titles, names, or headings where each word should be capitalized.
