William
William

Reputation: 23

Python convert a long string to a list without single quotes

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

Answers (3)

raton
raton

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

Paulo Scardine
Paulo Scardine

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

Nicolas
Nicolas

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

Related Questions