Python split a string containing a list

半腔热情 提交于 2021-02-10 06:25:34

问题


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?


回答1:


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']]


来源:https://stackoverflow.com/questions/47481361/python-split-a-string-containing-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!