How to capitalize each word of a given list of strings?

Question:

I need to satisfy this test:

def test_capitalize_names():
    assert ["James"] == capitalize_names(["JAMES"])
    assert ["Harry", "Jack"] == capitalize_names(["HArry", "jack"])

I tried writing capitalize_names like so:

def capitalize_names(input):
    input = map(lambda s: s.capitalize(), input)
    li = map(lambda x: '"'+x+'"', input)
    return li

It is returning ['"James"'] but I want it to return ["James"] to satisfy the assert statements and I cannot use any control statements.

Asked By: user9981154

||

Answers:

The fastest way is:

def capitalize_names(inp):
    return [i.capitalize() for i in inp]
def test_capitalize_names():
    assert ["James"] == capitalize_names(["JAMES"])
    assert ["Harry", "Jack"] == capitalize_names(["HArry", "jack"])
Answered By: U13-Forward

Try this:

def capitalize_names(input):
    return list(map(lambda s: s.capitalize(), input))

this is the efficient way of doing this.

Answered By: Mehrdad Pedramfar

A more succinct way: for example:

import string
def capitalize_names(lst_str):
    return map(string.capitalize, lst_str)

if __name__ == '__main__':
    print capitalize_names(["HArry", "jack", "JAMES"])
    # ['Harry', 'Jack', 'James']
Answered By: Jayhello
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.