Capitalize First Letter of Each Word in Python


If you have a sentence containing multiple words, and you want each of the words to start with a capital letter, then you can do one of the following:

Option 1 - using string.capwords()

import string

string.capwords('this is a test!')

Output: 'This Is A Test!'

Option 2 - using title()

'this is a test!'.title()

Output: 'This Is A Test!'

Option 3 - using join(), split() and list comprehensions

" ".join(w.capitalize() for w in 'this is a test!'.split())

Output: 'This Is A Test!'