Stefano
Stefano

Reputation: 85

Split string by considering multiple values

I'm trying to split the following type of string in Python 2.7 in order to convert it into a list of values:

s = "19, '8X','1Gb', '1.5 GHz dual-core',342,'4.3', '720x1280','32,35 x 66,2 x 10,12', 130, '', 4, 9"

I would like to get a list of values similar to:

list_s = [19, '8X', '1Gb', '1.5 GHz dual-core', 342, '4.3', '720x1280', '32,35 x 66,2 x 10,12', 130, ' ', 4, 9]

I tried to used the function split() and the function re.split() in the following way:

list_s = s.split(",")
#OUTPUT =  ['19', " '8X'", " '1Gb'", " '1.5 GHz dual-core'", ' 342', " '4.3'", " '720x1280'", " '32", '35 x 66', '2 x 10', "12'", ' 130', " ''", ' 4', ' 9']

list_s2 = re.split("([`]|[']|[\"]){1}[,]", s)
#OUTPUT =  ["19, '8X", "'", " '1Gb", "'", " '1.5 GHz dual-core", "'", " 342, '4.3", "'", " '720x1280", "'", " '32,35 x 66,2 x 10,12", "'", " 130, '", "'", ' 4, 9']

Can you suggest me a solution for this problem?

Upvotes: 0

Views: 71

Answers (2)

Jarvis
Jarvis

Reputation: 8564

Direct eval for the fixed, raw-string works well:

>>> s = "19, '8X','1Gb', '1.5 GHz dual-core',342,'4.3', '720x1280','32,35 x 66,2 x 10,12', 130, '', 4, 9"
>>> list(eval(s))
[19, '8X', '1Gb', '1.5 GHz dual-core', 342, '4.3', '720x1280', '32,35 x 66,2 x 10,12', 130, '', 4, 9]

However, do look at this. eval is certainly dangerous as mentioned in the comments and should be used only on static/fixed raw-strings you are sure about. In that case, the posted answer suggesting ast.literal_eval is the safest and correct choice.

Upvotes: 3

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48077

It's simpler to achieve this using ast.literal_eval():

>>> s = "19, '8X','1Gb', '1.5 GHz dual-core',342,'4.3', '720x1280','32,35 x 66,2 x 10,12', 130, '', 4, 9"
>>> import ast

>>> ast.literal_eval("[{}]".format(s))
[19, '8X', '1Gb', '1.5 GHz dual-core', 342, '4.3', '720x1280', '32,35 x 66,2 x 10,12', 130, '', 4, 9]

Refer "ast.literal_eval()" document for more details.

If you are going to use any solution using regex or str.split(), then after splitting the elements into strings, you'll have to explicitly type-cast the integers & floats to get your desired list.

Upvotes: 2

Related Questions