How to capitalize the first letter of each word in a String with Python?

Estimated read time 1 min read

You can capitalize the first letter of each word in a string with Python by using the title() method. Here’s an example:

text = "hello world"
title_text = text.title()
print(title_text)

In this example, the title() method is applied to the text string. This method returns a new string with the first letter of each word capitalized. Finally, the capitalized string is printed to the console.

If you want to modify the original string instead of creating a new one, you can use the split() method to separate the string into words, capitalize the first letter of each word, and then join the words back together using the join() method. Here’s an example:

text = "hello world"
words = text.split()
capitalized_words = [word.capitalize() for word in words]
capitalized_text = " ".join(capitalized_words)
print(capitalized_text)

In this example, the split() method is used to separate the text string into a list of words. The list comprehension is used to capitalize the first letter of each word, and the join() method is used to join the words back together using a space separator. Finally, the modified string is printed to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply