Search code examples
pythonstringlistnestedcapitalize

python capitalize nested list with strings and integers


I'm trying to capitalize the first letter for every word in this nested list, but I cannot seem to figure out how to make Python "ignore" the last elements 8 and 7 but still keep them in the list. (fyi, I have only had programming for about two weeks now, so it's all still quite new to me)

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

capitalize_nested([['Loraine','Jessica'],'Philip',['Dave', 'Jones'], 8, 7])

Hope to get some kind of hint or the like thanks in advance


Solution

  • If you are allowed to alter the input, then you can do it in-place, while iterating over the list:

    def capitalizeNested(L):
        for i,item in enumerate(L):
            if isinstance(item, list):
                L[i] = [it.title() for it in item]
            elif isinstance(item, str):
                L[i] = item.title()
    

    Output:

    In [54]: L = [['loraine','jessica'],'philip',['dave', 'jones'], 8, 7]
    
    In [55]: capitalizeNested(L)
    
    In [56]: L
    Out[56]: [['Loraine', 'Jessica'], 'Philip', ['Dave', 'Jones'], 8, 7]