String.capwords() method in Python


Borislav Hadzhiev

Last updated: Sep 7, 2022


Photo from Unsplash

String.capwords() method in Python #

The string.capwords method:

  1. Uses the str.split() method to split the string into words.
  2. Uses the str.capitalize() method to capitalize each word.
  3. Uses the str.join() method to join the capitalized words into a string.
from string import capwords my_str = 'bobby hadz com' result = capwords(my_str) print(result) # 👉️ 'Bobby Hadz Com'

The string.capwords() method converts the first character in each word to uppercase and the rest to lowercase.
from string import capwords my_str = 'BOBBY HADZ COM' result = capwords(my_str) print(result) # 👉️ 'Bobby Hadz Com'

You can also use the capwords() method if you need to capitalize the first letter of each word in a list.
from string import capwords my_list = ['bobby hadz', 'dot com'] result = [capwords(item) for item in my_list] print(result) # 👉️ ['Bobby Hadz', 'Dot Com']

We used a list comprehension to iterate over the list and passed each item to the capwords() method.

The string.capwords() method uses the str.capitalize() method on each word in the string.

The str.capitalize function returns a copy of the string with the first character capitalized and the rest lowercased.
print('bobby'.capitalize()) # 👉️ 'Bobby' print('HADZ'.capitalize()) # 👉️ 'Hadz'

Note that there is also a str.title() method.

The str.title method returns a titlecased version of the string where the words start with an uppercase character and the remaining characters are lowercase.
my_str = 'bobby hadz' result = my_str.title() print(result) # 👉️ "Bobby Hadz"

However, the algorithm also converts characters after apostrophes to uppercase.
my_str = "it's him" result = my_str.title() print(result) # 👉️ "It'S Him"

The string.capwords method doesn't have this problem, as it only splits the string on spaces.
from string import capwords my_str = "it's him" result = capwords(my_str) print(result) # 👉️ "It's Him"
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.