How do you capitalize the first letter of each word in a string using Python?
To capitalize the first letter of every word in Python using one line of code enter the following:
" ".join([x.upper() + x[1:] for x in my_string.split()]).
Here is an example demonstrating how the code works in the Python REPL:
>>> my_string = "How long is a piece of string?" >>> " ".join(x.upper() + x[1:] for x in my_string.split()]) 'How Long Is A Piece Of String?'
As you can see from the above example the output produces a string with each character capitalized.
Let’s explore how this one-liner works. To explore this code in a little more detail I’ll start from the right-hand side and work my way left, starting with the expression
How To Split A String Into Words
How can you split a string into words? You can easily do this by using the built-in string method
split(sep, maxsplit) function takes two parameters
sep which is the string delimiter to break up your string and
maxsplit as the maximum number of splits to perform.
sep is blank by default Python will separate the string based on consecutive whitespace characters while also trimming and leading or trailing whitespace.
Here’s an example of what this means:
>>> my_string = " Spaced out man. " >>> my_string.split() ['Spaced', 'out', 'man.']
Notice how the
split() function stripped out the leading and trailing spaces and it also merged those consecutive whitespace characters into one and just output the words (with punctuation).
If you don’t want the
split() function to do this, but still want to break your string by a single space character then insert the space character as the parameter, like so:
>>> my_string = " Spaced out man. " >>> my_string.split(" ") ['', '', '', 'Spaced', '', '', 'out', '', 'man.', '', '']
As you can see from this example the splits are now performed on each space character.
maxsplit parameter is blank or
-1 it will perform the split on the entire string, otherwise it will only split according to the number of times specified for this parameter.
So the first element with the one-liner code is to split each word into a list. By using the
split() string method you can easily break your string into a list of words.
Here’s how the one-liner works by looking at the
split() expression first:
>>> my_split = "How long is a piece of string?" >>> my_split.split() ['How', 'long', 'is', 'a', 'piece', 'of', 'string?']
As you can see from the above display the sentence is now a list broken up into words.
How To Use A List Comprehension
A list comprehension is a single line that allows users to loop through the contents of a list to create a new list.
The second part of the one-liner code is the
for loop that is inside a list comprehension. The basic aspect of this code looks like this
[x for x in my_string.split()].
for x in my_string.split() part of this code just loops through each element in the list which has each word of
my_string for its elements and assigns each element to the variable
x at the front of the
for loop part then tells Python what to do with each element. At the moment nothing is happening with each element.
If I wanted to apply the
upper() string method to each element then I could write the following code:
>>> my_string = "How long is a piece of string?" >>> [x.upper() for x in my_string.split()] ['HOW', 'LONG', 'IS', 'A', 'PIECE', 'OF', 'STRING?']
As you can see from the above code now I have a new list of uppercase characters from my original string.
How To Modify The First Character Of Each Word
To modify each element of the new list created from a list comprehension you need to operate on the left side of the
Therefore, as the objective is to change each word in
my_string to be capitalized I will use the built-in string method
.upper() to convert the first character, then I will append the remaining characters of the string.
Python has a handy slice operator which allows you to extract characters from a string. There are two different sub-strings you need when capitalizing the first character (1) the first character and (2) everything else after the first character.
To extract the first character from a string using the Python slice operator, simply use
my_string. To extract every other character after the first character use
Here’s what this would look like when used on a simple string:
>>> my_string = "first" >>> my_string 'f' >>> my_string[1:] 'irst' >>> my_string.upper() + my_string[1:] 'First'
As you can see from the above examples you can extract the first character by using the index reference, as this is permitted in Python with the string data type, you then can use the slice operator to get every other character in your string thereafter, and finally, you can apply the
.upper() string method on the index reference and stitch this together with the remaining part of the string to get the capitalized string you want.
What if you needed to force the remaining strings to all be lower case?
You could also modify this final operation to force the remaining characters of the string to be lower case using the other built-in function
Here’s an example where you can modify a string to capitalize the first character and force all other remaining characters to lower case:
>>> my_string = "hELLo" >>> my_string.upper() + my_string[1:].lower() 'Hello'
Whatever your choice on this operation you insert it before the
for loop inside the list comprehension and this will then perform the required capitalization on each element in the split list.
Here’s how the output appears up to this point:
>>> my_string = "How long is a piece of string?" >>> [x.upper() + x[1:] for x in my_string.split()] ['How', 'Long', 'Is', 'A', 'Piece', 'Of', 'String?']
As you can see you now have a list of strings with the first character capitalized.
How To Join A List Of Strings Together
The final step is to join the list of capitalized strings together into one string and this is done with another built-in string function
join() method can seem a little strange at first, as some other languages would have two parameters where the user enters the list and then the string to use to join each element in the list by, but in Python the format of the
join() string method is to operate the
join() on the string and to have the list inside its parameters.
It therefore looks like this:
Therefore, with our current working example, if I was to capture the list comprehension into a variable it would look something like this:
>>> my_string = "How long is a piece of string?" >>> my_caps_list = [x.upper() + x[1:] for x in my_string.split()] >>> " ".join(my_caps_list) 'How Long Is A Piece Of String?'
As you can see the
join() method is quite simple to use provided you know which elements go where: string outside, list inside.
To capitalize each word in a string using Python’s powerful features on one-line of code use the following:
" ".join([x.upper() + x[1:] for x in my_string.split()]) where
my_string refers to the variable you’re initiating with the original sentence string.