Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert and merge strings into a list in Python

In Python I have four strings that include the formatting of a list:

line1 ="['a.b.c','b.c.a','c.d.e']"
line2 ="['def','efg']"
line3 ="['f']"
line4 ="['g']"

How do I merge them all so I get a valid Python list such as:

SumLine = ['a.b.c','b.c.a','c.d.e','def','efg','f','g']
like image 867
greye Avatar asked Dec 06 '22 04:12

greye


2 Answers

import ast

line1 ="['a.b.c','b.c.a','c.d.e']"
line2 ="['def','efg']"
line3 ="['f']"
line4 ="['g']"

SumLine = []

for x in (line1, line2, line3, line4):
  SumLine.extend(ast.literal_eval(x))

print SumLine

Don't use the built-in eval unless you have preternatural trust in the strings you're evaluating; ast.literal_eval, while limited to simple constants, is totally safe and therefore, most often, way preferable.

like image 64
Alex Martelli Avatar answered Dec 10 '22 10:12

Alex Martelli


The simple way is to concetenate the strings to an expression that can be evaulated to give the required result:

line1 ="['a.b.c','b.c.a','c.d.e']"
line2 ="['def','efg']"
line3 ="['f']"
line4 ="['g']"
lines = [line1, line2, line3, line4]

print eval('+'.join(lines))

However this is unsafe if you can't trust your input, so if you're using Python 2.6 or higher you should use the safe eval function ast.literal_eval in the ast module, although this doesn't work with the '+' trick so you will have to iterate over each element instead.

like image 28
Mark Byers Avatar answered Dec 10 '22 09:12

Mark Byers