Start learning free

LESSON 218 OF 673 · LOOPS WITH STRINGS, LISTS & DICTIONARIES

Capitalize Each Word in Python: split, upper and join

Practice Read the full explanation

Given a string sentence, return the same sentence with the first letter of each word in upper case.

The words are separated by single spaces, and the sentence doesn't start or end with a space. Only the first character of each word changes: the rest of the word stays exactly as it is, even when it has upper-case letters. A first character that has no upper case, like a digit, stays as it is too.

 

Example 1:

Input: sentence = "hello world"
Output: "Hello World"
Explanation: h becomes H and w becomes W.

Example 2:

Input: sentence = "learn to code with AlgoCademy"
Output: "Learn To Code With AlgoCademy"
Explanation: AlgoCademy already starts with an upper-case letter, so it stays the same.

Example 3:

Input: sentence = "iPhone and NASA"
Output: "IPhone And NASA"
Explanation: Only the first character of each word changes: "Phone" and "ASA" stay as they were.

 

Constraints:

  • sentence has at least one word.
  • sentence contains English letters, digits and apostrophes, with single spaces between the words.
STEP 1 OF 6
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Capitalize Each Word in Python, explained

    Problem overview

    The function capitalizeWords receives a sentence and returns it with the first letter of each word in upper case. Words are separated by single spaces, and the sentence doesn't start or end with a space. Only the first character of each word changes. The rest of the word stays exactly as it is, even when it has upper-case letters, and a first character with no upper case, such as a digit, stays as it is too.

    For "hello world" the answer is "Hello World". For "iPhone and NASA" it is "IPhone And NASA": the Phone and ASA parts are untouched.

    Approach

    Python strings are immutable, so you can't change a letter in place. Instead, build each new word from two pieces: the first character in upper case, and the rest of the word unchanged. Then put the words back together.

    The plan has three parts: cut the sentence into words with split, fix each word and collect it in a new list, and glue the list into one string with join. Because the split and the join both use a single space, every space ends up where it started.

    Step by step

    1. Split the sentence at spaces with sentence.split(" "), which gives a list of words.
    2. Create an empty list named result. It will hold the fixed words in the same order.
    3. Loop over the words with a variable word.
    4. Build capitalized: word[0].upper() is the first character in upper case, and word[1:] is the slice from index 1 to the end, the rest of the word. A one-letter word works too, since its rest is an empty string.
    5. Append capitalized to result.
    6. Return " ".join(result). The string before the dot is placed between each two items of the list.

    The solution in Python

    class Solution:
        def capitalizeWords(self, sentence: str) -> str:
            words = sentence.split(" ")
            result = []
            for word in words:
                capitalized = word[0].upper() + word[1:]
                result.append(capitalized)
            return " ".join(result)
    

    Details worth knowing:

    • Slices don't fail at the end. word[1:] on a one-letter word is '', with no error, while word[1] would raise IndexError. So "a b c" becomes "A B C".
    • upper() returns a new string. Calling x[0].upper() by itself changes nothing: the original string stays hello. Assigning into a string, as in x[0] = "H", raises TypeError: 'str' object does not support item assignment.
    • Characters without a case. "3rd place" becomes "3rd Place". "3".upper() is "3", so a leading digit is left alone.
    • Apostrophes. "don't stop" becomes "Don't Stop". The apostrophe is inside the word, so it isn't a split point.
    • Why not capitalize() or title()? The method "NASA".capitalize() gives "Nasa", because it lowers the rest of the word, and "iPhone and NASA".title() gives "Iphone And Nasa". Both break the rule that the rest of the word stays as it is. "don't stop".title() gives "Don'T Stop", too.

    Edge cases and common mistakes

    • A single word. split(" ") returns a list with one item, so "hello" becomes "Hello".
    • Letters after the first. Applying upper() to the whole word would turn "iPhone" into "IPHONE". Only the first character should change.
    • Double spaces. The lesson promises single spaces. If a sentence had two in a row, split(" ") would produce an empty word in between, and word[0] would fail on it with IndexError: string index out of range.
    • Forgetting the join. Returning result gives a list, not a string.
    • Joining with no space. "".join(result) gives "HelloWorld". The separator is the string before the dot.

    Testing

    • "hello world" gives "Hello World".
    • "learn to code with AlgoCademy" gives "Learn To Code With AlgoCademy".
    • "iPhone and NASA" gives "IPhone And NASA".
    • "a b c" gives "A B C".
    • "3rd place" gives "3rd Place".
    • "don't stop" gives "Don't Stop".
    Keep going with Python650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free