Summary: in this tutorial, you’ll learn how to use the Python string
title() method to convert a string to titlecase.
Introduction to the Python title() method
The titlecase is a capitalization style used for titles so that the first letter of each word is uppercase and the remaining letters are lowercase. For example:
Python Title Case TutorialCode language: PHP (php)
The rules for the titlecase, however, are not universally standardized.
To make titlecased version of a string, you use the string
title() method. The
title() returns a copy of a string in the titlecase.
title() method converts the first character of each words to uppercase and the remaining characters in lowercase.
The following shows the syntax of the
str.title()Code language: CSS (css)
Python title() method example
The following example shows how to use the
title() method to return the titlecased version of a string:
name = 'john doe'.title() print(name)Code language: PHP (php)
Python title() method limitation
title() method defines a word as a group of consecutive letters.
This rule works in many contexts. However, it won’t work as you may expect if a string contains the apostrophes (‘) like contractions and possessives. For example:
s = "They're john's relatives.".title() print(s)Code language: PHP (php)
In this example, the string contains apostrophes (
') that act as word boundaries. The
title() method treats
They're as two separate words.
To fix it, you need to define a function that uses a regular expression:
And use the
s = "They're john's relatives." s = titlecase(s) print(s)Code language: PHP (php)
Now, it works as expected.
- Use the Python string
title()method to returns the titlecased version of a string.