Akash Vibhute Akash Vibhute - 2 months ago 8
Python Question

Convert list of list of integers into a list of strings

I have a list of list:

['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]']


I want output to look like

['28','82','253',2530',5302']


I've tried using

string1= ''.join(str(e) for e in list[0])


I get output for print (string1) as:

[2, 8]


What am i doing wrong here?

Answer

You actually don't have a list of list, you have a list of str. Therefore you can use ast.literal_eval to interpret each string as a list, then convert to str and join.

>>> l = ['[2, 8]', '[8, 2]', '[2, 5, 3]', '[2, 5, 3, 0]', '[5, 3, 0, 2]']
>>> from ast import literal_eval
>>> [''.join(str(j) for j in literal_eval(i)) for i in l]
['28', '82', '253', '2530', '5302']
Comments