0

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Stefano
  • 85
  • 7

2 Answers2

3

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.

Jarvis
  • 8,494
  • 3
  • 27
  • 58
2

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.

Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126