Python String title() Function
The String title()
method returns a new string with the first character of each word to uppercase and the remaining characters to lowercase. It is particularly useful for formatting strings as titles or headers.
The method does not change the original string.
Syntax
my_string.title()
title() Parameters
Python String title()
function does not take any parameters.
title() Return Value
Python String title()
function returns a new string with the first character of each word capitalized and all other characters in lowercase.
Examples
Example 1: Title Case a String with title()
The title()
method returns a new string with the first character of each word capitalized and all other characters in lowercase.
my_str = 'hello world!'
result = my_str.title()
print(result) # Output: Hello World!
output
Hello World!
Example 2: Title Case a Mixed Case String with title()
The title()
method works also with mixed case strings.
my_str = 'tUtORiaL rEFerENce!'
result = my_str.title()
print(result) # Output: Tutorial Reference!
output
Tutorial Reference!
Example 3: Title Case an All Uppercase String with title()
The title()
method works also with all upper case strings.
my_str = 'TUTORIAL REFERENCE!'
result = my_str.title()
print(result) # Output: Tutorial Reference!
output
Tutorial Reference!
Example 3: Title Case a String with Special Characters with title()
The behaviour of title()
method is unexpected in presence of special characters in the string: the first letter after every number or special character is considered as the start of a new word and so converted into a upper case letter.
For example, you have that:
my_str = "let's go back to the 80s"
result = my_str.title()
print(result) # Output: Let'S Go Back To The 80S
my_str = "we're tutorial reference."
result = my_str.title()
print(result) # Output: We'Re Tutorial Reference.
output
Let'S Go Back To The 80S
We'Re Tutorial Reference.
Workaround
A workaround for this problem is string.capwords()
.
It is an helper function of string
package that:
- Split the argument into words using
split()
- Capitalize each word using
capitalize()
- Join the capitalized words using
join()
import string
my_str = "let's go back to the 80s"
result = string.capwords(my_str)
print(result) # Output: Let's Go Back To The 80s
my_str = "we're tutorial reference."
result = string.capwords(my_str)
print(result) # Output: We're Tutorial Reference.
output
Let's Go Back To The 80s
We're Tutorial Reference.