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']
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With