Python: Capitalize the Beginning of Every Word in a String
In this tutorial, we will learn how to capitalize the first character of every word in a string in Python.
Capitalize the Start of Each Word with the Python .title() Function
Python has a built-in function that will transform the first letter of each word in a string to uppercase called title()
. Pass the string before the function and store the result in a variable like this:
text = 'some text to capitalize'
result = text.title()
print(result)
Some Text To Capitalize
A nice feature of the Python title()
function is that it will automatically lowercase letters all chars except those at the start of a word. Here is an example of a string containing mixed case wording:
text = 'some TeXT tO capiTalize'
result = text.title()
print(result)
Some Text To Capitalize
One issue with the title()
function is that it doesn't consider punctuation in words and will capitalize the letter after an apostrophe to name one example.
text = "that's"
result = text.title()
print(result)
That'S
Not ideal. Fortunately, we can use the capwords() function instead.
Capitalize First Letter of Each Word in a String with Punctuation
Here is an example of using the function string.capwords()
function to uppercase the first letter of each word in a string that contains punctuation.
import string
text = "that's great"
result = string.capwords(text)
print(result)
That's Great
There is of course another potential issue if the string contains acronyms that should be in uppercase. If you expect those, a custom function is needed, which will use a list of acronyms to ignore.