The primary difference between str.capitalize() and str.title() lies in their scope of capitalization. str.capitalize() only capitalizes the first character of the entire string and str.title() capitalizes the first character of every word in the string. Let's understand both str.capitalize() and str.title() and difference between both in detail:
title() method
title() function in Python is the Python String Method which is used to convert the first character in each word to Uppercase and the remaining characters to Lowercase in the string and returns a new string.
Syntax: str.title()
Returns: This function returns a string which has first letter in each word is uppercase and all remaining letters are lowercase.
Example:
# Example 1: Simple string
s = "geeksforgeeks"
res = s.title()
print(res)
# Example 2: Mixed case string
s = "GFG"
res = s.title()
print(res)
# Example 3: String with non-alphabetic characters
s = "hello world"
res = s.title()
print(res)
Output
Geeksforgeeks Gfg Hello World
capitalize() method
In Python, the capitalize() method converts the first character of the first word of a string to a capital (uppercase) letter.
Syntax: str.capitalize()
Return Type: This function returns a string that has the first letter of the first word in uppercase and all remaining letters of the first word in lowercase.
Example:
# Example 1: Simple string
s = "hello world"
res = s.capitalize()
print(res)
# Example 2: Mixed case string
s = "PYTHON programming"
res = s.capitalize()
print(res)
# Example 3: String with numbers or symbols
s = "123abc"
res = s.capitalize()
print(res)
Output
Geeks for geeks GeeksForGeeks
Comparison Between str.capitalize() and str.title()
Criteria | str.capitalize() | str.title() |
|---|---|---|
Function | Capitalizes only the first character of the entire string. | Capitalizes the first character of every word in the string. |
Case Conversion | Converts all other characters to lowercase. | Leaves the case of non-initial characters unchanged. |
Word Delimiter Handling | Does not consider word boundaries or delimiters. | Treats spaces, hyphens (-), underscores (_) and similar characters as word separators. |
Input Impact | Works on the entire string as a single unit. | Processes each word independently. |
Special Characters | Does not affect non-alphabetic characters. | Non-alphabetic characters act as delimiters, but remain untouched. |
Use Case | Formatting the start of a sentence. | Formatting titles, headings or names. |