Reputation: 23
I have a long string that I want store it as a list. But it always has single quotes at the beginning and the end. How to remove them? Thanks.
Samples
>>> string
>>> '"2012-11-05", "filename", 1, 2, 3, 4, 5, 6, 7, 0.11, 0.22, 0.33'
>>> string.split("'")
>>> ['"2012-11-05", "filename", 1, 2, 3, 4, 5, 6, 7, 0.11, 0.22, 0.33']
Question is how can I get result like this below without single quotes?
>>> ["2012-11-05", "filename", 1, 2, 3, 4, 5, 6, 7, 0.11, 0.22, 0.33]
Upvotes: 1
Views: 3303
Reputation: 428
python 3.2
string='"2012-11-05", "filename", 1, 2, 3, 4, 5, 6, 7, 0.11, 0.22, 0.33'
a=eval(string)
res=list(a)
Upvotes: -1
Reputation: 77329
Your data seems to be a valid python tuple.
import ast
list(ast.literal_eval('"2012-11-05", "filename", 1, 2, 3, 4, 5, 6, 7, 0.11, 0.22, 0.33'))
The literal_eval function from the ast module is safer than plain eval, because literal_eval will not evaluate arbitrary code, just plain values.
Upvotes: 9
Reputation: 5678
Try this:
[s.replace('"', '').strip() for s in string.split(',')]
>>> ['2012-11-05', 'filename', '1', '2', '3', '4', '5', '6', '7', '0.11', '0.22', '0.33']
Upvotes: 3