This concise and straightforward article will show you four different ways to capitalize the first letter of each word in a given string in Python.
Using the title() method (easiest approach)
str.title() is a built-in method of Python that capitalizes the first letter of each word in a string. It can help us get the job done with just a single line of code.
string = "He thrusts his fists against the posts and still insists he sees the ghosts" capitalized_string = string.title() print(capitalized_string)
He Thrusts His Fists Against The Posts And Still Insists He Sees The Ghosts
Using the string.capwords() function
The helper function
string.capwords() can also help you get the desired result conveniently. But wait, you have to import the
string module first.
import string text = "The battle of electric cars versus gas cars is over. Electric cars won." title = string.capwords(text) print(title)
The Battle Of Electric Cars Versus Gas Cars Is Over. Electric Cars Won.
Using the split(), capitalize(), and join() methods
This is a three-step process:
- Split your string into words using the
- Capitalize each word using the
- Join the words back into a string using the
string = "He is the man who sold the world to the devil." words = string.split() capitalized_words = [word.capitalize() for word in words] capitalized_string = " ".join(capitalized_words) print(capitalized_string)
He Is The Man Who Sold The World To The Devil.
Using regular expressions
The strategy here is to use the
re.sub() function from the
re module to match each word using a regular expression pattern and capitalize it using a lambda function.
import re text = "A lonewolf is a person who avoids associating with other people." capitalized_string = re.sub( r"\b\w", lambda m: m.group().upper(), text ) print(capitalized_string)
A Lonewolf Is A Person Who Avoids Associating With Other People.
That’s it. Choose the method that suits your coding style and go with it. Good luck & enjoy your day!