Python String title()

5/5 - (1 vote)

Python’s built-in string.title() method returns a new string that has uppercase first characters for each word.

Minimal Example

>>> 'top 10 python cheat sheets'.title()
'Top 10 Python Cheat Sheets'

As you read over the explanations below, feel free to watch our video guide about this particular string method:

Python String Methods [Ultimate Guide]

Syntax and Explanation

str.title()

Returns a new string with uppercase first characters of each word.

💡 Info: A title cased string is a string where each word starts with an uppercase letter—but only the first character of each word is capitalized.

👉 Recommended: Generating Random Titles Using a Simple Python Script

Good Examples

Here are three example strings that are transformed to title cased strings with capitalized first letters:

>>> 'hello world'.title()
'Hello World'
>>> 'are you a master coder?'.title()
'Are You A Master Coder?'
>>> 'the top 10 python tricks'.title()
'The Top 10 Python Tricks'

Bad Counter Examples — And How to Solve Them

Note that the algorithm to “title-case a string” is not perfect.

For example, it’ll transform abbreviations into the simplified title case form whereas only the first letters of each word are capitalized, although we may intend to capitalize even more letters for abbreviations and other strings:

>>> 'who is the next US president?'.title()
'Who Is The Next Us President?'

Python’s regular expression library can help you accomplish even more fine-grained, customized title case transformations.

How to Title Case a Python String with All-Uppercase Abbreviations

How to write code to title case a Python string so that all-uppercase abbreviations remain all-uppercase? Use Python regular expressions!

Example:

# Input
s = 'I go to US visiting the NASA space center'

# Desired output
'I Go To US Visiting The NASA Space Center'

# Real output:
'I Go to Us Visiting The Nasa Space Center'

Here’s the solution:

import re

s = 'I go to US visiting the NASA space center'

#pattern to identify abbreviations
pattern = re.compile('[A-Z]{2,}')

#split string and title case each word
words = s.split(' ')
title_words = [word.title() if not pattern.match(word) else word for word in words]

#join title case words
title_string = ' '.join(title_words)

print(title_string)

The output:

I Go To US Visiting The NASA Space Center

The code first imports the regular expression module re.

Next, it defines a pattern that looks for all-uppercase abbreviations. The string is then split into separate words and a list comprehension is used to title case each word, except for words that match the pattern (i.e., all-uppercase abbreviations).

Finally, the list of title-cased words is joined together to form a title-cased string.

Python String title() vs uppercase()

The Python string method title() returns a string with the first letter of each word capitalized and all other letters in the word lowercase. Conversely, the string.upper() method returns a string with all letters in the string capitalized.

Here’s a minimal Python example that shows the difference:

string1 = "hello world"
string2 = "HELLO WORLD"

print(string1.title()) # Output: Hello World
print(string2.title()) # Output: Hello World
print(string1.upper()) # Output: HELLO WORLD
print(string2.upper()) # Output: HELLO WORLD

Python String title() vs capitalize()

The Python string method title() returns a string with the first letter of each word capitalized and all other letters in the word lowercase. Conversely, the string.capitalize() method returns a string with only the first letter of the string capitalized, and any other letters in the word lowercase.

For example:

string1 = "hello world"
string2 = "HELLO WORLD"

print(string1.title()) # Output: Hello World
print(string2.title()) # Output: Hello World
print(string1.capitalize()) # Output: Hello world
print(string2.capitalize()) # Output: Hello world

More String Methods

Python’s string class comes with a number of useful additional string methods. Here’s a short collection of all Python string methods—each link opens a short tutorial in a new tab.

MethodDescription
capitalize()Return a copy of the string with capitalized first character and lowercased remaining characters.
casefold()Return a lowercased, casefolded string similar to lowercase() but more aggressive.
center()Return a centered string of a certain length, padded with whitespace or custom characters.
count()Return the number of non-overlapping occurrences of a substring.
encode()Returns a byte object that is an encoded version of the string.
endswith()Returns whether the string ends with a given value or not (True or False).
expandtabs()Return a string with spaces instead of tab characters.
find()Returns the index of the first occurrence of the specified substring.
format()Formats the string according to the Format Description Language.
format_map()Formats the string according to the Format Description Language, passing a mapping object.
index()Returns the index of the first occurrence of the specified substring, like find() but it raises a ValueError if the substring is not found.
isalnum()Checks whether all characters are alphabetic or numeric (True or False).
isalpha()Checks whether all characters are alphabetic (True or False).
isascii()Checks whether all characters are ASCII (True or False).
isdecimal()Checks whether all characters are decimal numbers (True or False).
isdigit()Checks whether all characters are digits, i.e., numbers from 0 to 9 (True or False).
isidentifier()Checks whether all characters are identifiers that can be used as names of functions, classes, or variables (True or False).
islower()Checks whether all characters are lowercase (True or False).
isnumeric()Checks whether all characters are numeric values (True or False).
isprintable()Checks whether all characters are printable (True or False).
isspace()Checks whether all characters are whitespaces (True or False).
istitle()Checks if the string is title-cased (True or False).
isupper()Checks whether all characters are uppercase (True or False).
join()Concatenates the elements in an iterable.
ljust()Returns a left-justified string filling up the right-hand side with fill characters.
lower()Returns a lowercase string version.
lstrip()Trims whitespaces on the left and returns a new string.
maketrans()Returns a translation table.
partition()Searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it.
removeprefix()Return string[len(prefix):] if the string starts with prefix, and string[:] otherwise.
removesuffix()Return string[:-len(suffix)] if the string starts with suffix, and string[:] otherwise.
replace()Returns a string with replaced values.
rfind()Return the highest index in the string where a substring is found. Returns -1 if not found.
rindex()Return the highest index in the string where a substring is found. Returns ValueError if not found.
rjust()Returns a right-justified string filling up the left-hand side with fill characters.
rpartition()Searches for a separator substring and returns a tuple with three strings: (1) everything before the separator, (2) the separator itself, and (3) everything after it.
rsplit()Splits the string at a given separator and returns a split list of substrings.
rstrip()Trims whitespaces on the right and returns a new string.
split()Splits the string at a given separator and returns a split list of substrings.
splitlines()Splits the string at line breaks such as '\n' and returns a split list of substrings (i.e., lines).
startswith()Returns whether the string starts with a given value or not (True or False).
strip()Trims whitespaces on the left and right and returns a new string.
swapcase()Swaps lowercase to uppercase characters and vice versa.
title()Returns a new string with uppercase first characters of each word.
translate()Returns a translated string.
upper()Returns a lowercase string version.
zfill()Fills the string from the left with "0" characters.

Docs