3

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.

costaparas
  • 5,047
  • 11
  • 16
  • 26
mslee017
  • 59
  • 1
  • 5
  • 2
    The issue here is that you aren't saving it when you do `word.capitalize()` so still `split_phrase` has not been updated, but see below of how to use the built-in `str.title` function – astrochun Feb 21 '21 at 06:05

2 Answers2

12

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
3

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.

costaparas
  • 5,047
  • 11
  • 16
  • 26