How can I capitalize the first letter of every word in a string in Python?

How can I capitalize the first letter of every word in a string in Python?

For example, if I have the string:

s = 'the brown fox'

I want s to be:

'The Brown Fox'

What’s the easiest way to Python capitalize the first letter of every word in a string?

The title() method converts the first character of each word to uppercase and all other characters to lowercase.

s = 'the brown fox'
s = s.title()
print(s)  # Output: 'The Brown Fox'

This is a simple and efficient way, but be aware that it also converts other letters in the words to lowercase.

Using a list comprehension with capitalize(): You can use a list comprehension along with the capitalize() method to make each word start with a capital letter.

s = 'the brown fox'
s = ' '.join([word.capitalize() for word in s.split()])
print(s)  # Output: 'The Brown Fox'

This is a simple and efficient way, but be aware that it also converts other letters in the words to lowercase.

ou can loop through each word, apply capitalize() and then join them back together.

s = 'the brown fox'
words = s.split()
for i in range(len(words)):
    words[i] = words[i].capitalize()
s = ' '.join(words)
print(s)  # Output: 'The Brown Fox'