Convert and concatenate strings into a list in Python

In Python, I have four lines that enable list formatting:

line1 ="['abc','bca','cde']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" 

How to combine them all to get the correct Python list, for example:

 SumLine = ['abc','bca','cde','def','efg','f','g'] 
+4
source share
6 answers

A simple way is to match strings with an expression that can be calculated to give the desired result:

 line1 ="['abc','bca','cde']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" lines = [line1, line2, line3, line4] print eval('+'.join(lines)) 

However, this is unsafe if you cannot trust your inputs, so if you are using Python 2.6 or higher, you should use the safe function eval ast.literal_eval in the ast module, although this does not work with '+', so you have to iterate through to every element.

+2
source
 import ast line1 ="['abc','bca','cde']" line2 ="['def','efg']" line3 ="['f']" line4 ="['g']" SumLine = [] for x in (line1, line2, line3, line4): SumLine.extend(ast.literal_eval(x)) print SumLine 

Do not use the built-in eval unless you have supernatural trust in the strings you evaluate; ast.literal_eval , although limited to simple constants, is completely safe and therefore most often preferred.

+11
source

Try eval :

 >>> line1 ="['abc','bca','cde']" >>> line2 ="['def','efg']" >>> line3 ="['f']" >>> line4 ="['g']" >>> eval(line1) + eval(line2) + eval(line3) + eval(line4) ['abc', 'bca', 'cde', 'def', 'efg', 'f', 'g'] 

But be careful, because eval can be dangerous. Do not use it on the input that you receive from the user, and did not confirm it.

+1
source

A quick and dirty way is to use eval :

 SumLine = eval(line1) + eval(line2) + eval(line3) + eval(line4) 

But do not do this if you get these lines from someone else (i.e. user input)

+1
source

Where did you get these lines? Anything smaller than a real analyzer will be fragile. Below I recommend that if I had not seen Alex Martelli's brilliant answer before!

You can parse them as JSON arrays, but JSON wants to read strings with double quotes, not single quotes. This introduces fragility into the method, but is still much preferable to eval() , which is unsafe.

 import json line1 ="['abc','bca','cde']" json.loads(line1.replace("'", '"')) 

As a result, the analyzed list, for example [u'a.b.c', u'b.c.a', u'c.d.e'] , you can join the analyzed lists.

+1
source

you need to eval them first, and then you can summarize the results. But I wonder how you get these lines in the first place?

0
source

All Articles