Given a list of words (text), i want to take each word except the first one and capitalize it. It doesn't work for neither i.capitalize() and i = i.capitalize(). Why?
def capitalize_words(text):
for i in text[1:]:
i.capitalize()
return text
CodePudding user response:
Use should return the modified data:
def capitalize_words(text):
return " ".join([i.capitalize() for i in text])
CodePudding user response:
The problem that you return the original list without mutate its values. The line i.capitalize()
has no affect on the output of your function.
Instead, you can populate a new list and return it, for example:
def capitalize_words(text):
capit_text = []
for i in text[1:]:
capit_text.append(i.capitalize())
return capit_text
or, using list comprehension:
def capitalize_words(text):
return [i.capitalize() for i in text[1:]]
CodePudding user response:
Because you return the original list that has not been changed
def capitalize_words(text):
return [word.capitalize() for word in text[1:]]
and if you want also text[0]
but not capitalized
return [text[0]] [word.capitalize() for word in text[1:]]