Capitalize the first letter of each word in a string in Python

Viewed 1988

Having a slight problem with this function in Python that's supposed to return the first letter of every word in a string capitalized and everything else lowercased:

def titleize(phrase):
    split_phrase = phrase.split()

    for word in split_phrase:
        word.capitalize()

    return ' '.join(split_phrase)

titleize('oNLy cAPITALIZe fIRSt') -> oNLy cAPITALIZe fIRSt

Clearly the issue is with the loop over the phrase (I think) that is being split and I suspect it's not mutating but rather creating something new but I'm stuck trying to fix it.

2 Answers

Might I suggest the use of the built-in str.title() function?

def titleize(phrase):
    capitalize_first = phrase.title()
    return capitalize_first
    
print(titleize('oNLy cAPITALIZe fIRSt'))

Output:

Only Capitalize First

You aren't assigning the result anywhere -- the split_phrase variable doesn't change at any point.

You could use str.title() as suggested by @pythonenthusiast, or use a list comprehension to simplify your current approach:

def titleize(phrase):
    return ' '.join([word.capitalize() for word in phrase.split()])

The corrected version of your original code could look like this:

def titleize(phrase):
    split_phrase = phrase.split()
    result = []
    for word in split_phrase:
        result.append(word.capitalize())
    return ' '.join(result)

Here, a new result list is created, and in each iteration, we append the changed word to the list. At the end, we join and return the new result list.

Related