Python: Capitalize the First Letter of each Word in a String

Updated: June 1, 2023 By: Wolf Post a comment

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.

Example:

string = "He thrusts his fists against the posts and still insists he sees the ghosts"
capitalized_string = string.title()
print(capitalized_string)

Output:

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.

Example:

import string

text = "The battle of electric cars versus gas cars is over. Electric cars won."
title = string.capwords(text)
print(title)

Output:

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:

  1. Split your string into words using the split() method.
  2. Capitalize each word using the capitalize() method.
  3. Join the words back into a string using the join() method.

Example:

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) 

Output:

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.

Example:

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) 

Output:

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!