Convert string to title case in Python
Last Updated :
07 Jan, 2025
Improve
In this article, we will see how to convert the string to a title case in Python. The str.title()
method capitalizes the first letter of every word.
s = "geeks for geeks"
result = s.title()
print(result)
Output
Geeks For Geeks
Explanation:
- The s.title() method converts the string
"python is fun"
to title case. - capitalizing the first letter of each word and converting the rest to lowercase, resulting in
"Geeks For Geeks"
.
Table of Content
Using the string.capwords()
The string.capwords()
function splits the text into words capitalizes the first letter of each word, and joins them back together with spaces.
import string
s = "geeks for geeks"
# Use the capwords() function to capitalize the first letter of each word
result = string.capwords(s)
print(result)
Output
Geeks For Geeks
Explanation:
- The
string.capwords()
function splits the input string"geeks for geeks"
into words based on spaces, capitalizes the first letter of each word, and converts the rest to lowercase. - Finally, it joins the words back together with spaces, resulting in
"Geeks For Geeks"
Using a List Comprehension
Manually capitalize each word in a string using a list comprehension and the str.capitalize()
method.
s = "geeks for geeks"
# Split the string into a list of words, capitalize each word,
#and join them back with spaces
result = " ".join(word.capitalize() for word in s.split())
print(result)
Output
Geeks For Geeks
Explanation
- The
s.split()
method splits the string"geeks for geeks"
into a list of words:["geeks", "for", "geeks"]
. Each word is then capitalized usingword.capitalize()
inside a generator expression. - The
" ".join()
method combines the capitalized words back into a single string with spaces, resulting in"Geeks For Geeks"
.