exergy
exergy

Reputation: 116

Convert string to nested tuple : Python

I have a string which looks like this:

a = '((1,2),(2,3))'

and I want to access it such that:

a[0] = (1,2)
a[0][1] = 2

I'd like to have it in a nested tuple form.

However nothing I do seems to work.

If it weren't a string, it works. However I am getting a string input from another source and that is why I am trying to do something like this.

a = ((1,2),(2,3))
print a[0][1]
# prints 2 ..it works fine

EDIT: I am sorry if I oversimplified my question. My actual data looks like:

a = '((243, SEA, ATL, 2013-08-12 05:50:00), (243, ATL, LAX, 2013-08-22 12:30:00),(243, LAX, SEA, 2013-05-29 18:10:00))'

This is a string I am reading. and I would like to split it by brackets (),() so that I can sort my data chronologically and rearrange it.

any ideas on how to go about it?

the liteal_eval does indeed work on the sample data I posted earlier. But it doesnt work for the above case.

The way I'm doing it now is : by replacing '),(' with ';' and removing all brackets '(',')' and then splitting by ';'

Is there a faster/better way?

Upvotes: 3

Views: 802

Answers (3)

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

If you want the data in one list use re:

a = '((243, SEA, ATL, 2013-08-12 05:50:00), (243, ATL, LAX, 2013-08-22 12:30:00),(243, LAX, SEA, 2013-05-29 18:10:00))'

import re

print re.findall("([^(]*)\)", a[1:-1])
['243, SEA, ATL, 2013-08-12 05:50:00', '243, ATL, LAX, 2013-08-22 12:30:00', '243, LAX, SEA, 2013-05-29 18:10:00']

Upvotes: 0

johntellsall
johntellsall

Reputation: 15170

Another solution is this one:

for row in data.split('), ('):
   for field in (f.strip() for f in row.split(',')):
      print field

If the data has commas, or embedded UTF8, consider using the csv module. It's much smarter, and is able to handle quoting and other types of edge cases.

Upvotes: 0

shaktimaan
shaktimaan

Reputation: 12092

ast module's literal_eval method is what you are looking for:

>>> import ast
>>> a = '((1,2),(2,3))'
>>> b = ast.literal_eval(a)
>>> b[0]
(1, 2)
>>> b[0][1]
2

Upvotes: 7

Related Questions