Nirod
Nirod

Reputation: 25

Python split a string containing a list

I would like to split a line from a file, but got stuck. Let's say i have this line in my file:

John, Smith, 1580, ["cool","line","splitting"]

Now I tried to make this:

line = line.split(',')
print line

Of course it returns:

['John', ' Smith', ' 1580', ' ["cool"', '"line"', '"splitting"]']

The problem is the list from file. I can't read it properly. I want it to look something like:

['John', 'Smith', 1580, ["cool", "line", "splitting"]]

Can someone help me do it this way?

Upvotes: 2

Views: 110

Answers (1)

Ajax1234
Ajax1234

Reputation: 71471

You can use ast.literal_eval:

import ast
import re
line = 'John, Smith, 1580, ["cool","line","splitting"]'
final_line = [ast.literal_eval(i) if i.startswith('[') else int(i) if re.findall('^\d+$', i) else i for i in re.split(',\s*', line)]

Output:

['John', 'Smith', 1580, ['cool', 'line', 'splitting']]

Upvotes: 3

Related Questions