Search code examples
pythonfunctioncapitalize

Function that takes a nested list of strings and returns a new nested list with all strings capitalized?


This will capitalize them but only if there are no nested lists.

t = ['this','that', ['other']]

def capitalize_nested(t):
    res = []
    for s in t:
        res.append(s.capitalize())
    return res

print capitalize_nested(t)

I can't figure out how to get it to print out a nested list having all of the strings start with a capital letter. I must be missing something obvious, this just has me stumped.


Solution

  • Use a recursive solution (and using list comprehensions also helps make it more compact):

    def capitalize_nested(t):
        if isinstance(t, list):
            return [capitalize_nested(s) for s in t]
        else:
            return t.capitalize()
    

    For example:

    print capitalize_nested(['this', 'that', ['other']])
    # ['This', 'That', ['Other']]