Function that takes a nested list of strings and returns a new nested list with all strings capitalized?
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']]
def cap(L):
for i,elem in enumerate(L):
if isinstance(elem, str):
L[i] = elem.capitalize()
elif isinstance(elem, list):
cap(L[i])
Just check if s
is a list then recursively call your capitalize_nested
function:
t = ['this','that', ['other']]
def capitalize_nested(t):
res = []
for s in t:
if type(s) == list:
res.append(capitalize_nested(s))
else:
res.append(s.capitalize())
return res
print capitalize_nested(t)