Geesh_SO
Geesh_SO

Reputation: 2205

How do I parse a CSV list enclosed in brackets in Python?

I'd like to parse the following raw string into an array:

(65.312321,89.314213214214)

Being Python, I'd bet there is a beautiful way to do this, I just don't know it!

Upvotes: 0

Views: 328

Answers (2)

Abhijit
Abhijit

Reputation: 63757

In Python you do not have array's. You either end up having data in an immutable tuple or a mutable List. Your best bet is to use ast for this purpose

>>> import ast
>>> st = "(65.312321,89.314213214214)"
>>> ast.literal_eval(st) # as a tuple
(65.312321, 89.314213214214)
>>> list(ast.literal_eval(st)) # as a list
[65.312321, 89.314213214214]

You may if you desire can also strip out the parenthesis and split by comma

>>> st.strip("() ").split(",")
['65.312321', '89.314213214214']

Upvotes: 3

Pavel Anossov
Pavel Anossov

Reputation: 62928

Since it's syntactically equivalent to python's tuple of floats, you can use ast.literal_eval:

>>> import ast
>>> print ast.literal_eval("(65.312321,89.314213214214)")
(65.312321, 89.314213214214)

If you want, you can convert it to a list:

>>> print list(ast.literal_eval("(65.312321,89.314213214214)"))
[65.312321, 89.314213214214]

Upvotes: 4

Related Questions