The difference between Python title vs capitalize functions is how they convert (return) a string.
Where the title() function changes the first character in each word to Uppercase and the remaining characters to Lowercase in the string and returns a new string.
str.title()
And the capitalize() method converts the first character of a string to a capital (uppercase) letter.
str.capitalize()
Here’s a comparison of the capitalize()
and title()
functions in tabular format:
Function | Purpose | Example Input | Output |
---|---|---|---|
capitalize() | Capitalize the first character of each word | “hello world” | “Hello world” |
title() | Capitalize first character of each word | “hello world” | “Hello World” |
Example difference title vs capitalize in Python
A simple example code title() changes every word, but capitalize() only the first word in a sentence:
a = 'silly question'
print(a.title())
a = 'silly question'
print(a.capitalize())
Output:
As you can see, the capitalize()
function capitalizes only the first character of the entire string, while the title()
function capitalizes the first character of each word in the string.
Do comment if you have any doubts or suggestions on this Python comparison topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.