4

I like to convert in a Python script the following string:

mystring='(5,650),(235,650),(465,650),(695,650)'

to a list of tuples

mytuple=[(5,650),(235,650),(465,650),(695,650)]

such that print mytuple[0] yields:

(5,650)
glglgl
  • 89,107
  • 13
  • 149
  • 217
Jean-Pat
  • 1,839
  • 4
  • 24
  • 41

3 Answers3

13

I'd use ast.literal_eval:

In [7]: ast.literal_eval('(5,650),(235,650),(465,650),(695,650)')
Out[7]: ((5, 650), (235, 650), (465, 650), (695, 650))

As seen above, this returns a tuple of tuples. If you want a list of tuples, simply apply list() to the result.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
1

That's not a tuple, that's a list.

If you can depend on the format being exactly as you've shown, you can probably get away with doing something like this to convert it to a list:

mystring2 = mystring.translate(None, "()")
numbers = mystring2.split(",")
out = []
for i in xrange(len(numbers) / 2)
  out.append((int(numbers[2 * i), int(2 * i + 1])))

This can probably be improved using some better list-walking mechanism. This should be pretty clear, though.

If you really really want a tuple of tuples, you can convert the final list:

out2 = tuple(out)
unwind
  • 391,730
  • 64
  • 469
  • 606
1

Use eval

mytuple = eval(mystring)

If you want a list enclose mystring with brackes

mytuble=eval("[%s]" % mystring)

That's the 'simplest' solution (nothing to import, work with Python 2.5) However ast.literate_eval seems more appropriate in a defensive context.

mb14
  • 22,276
  • 7
  • 60
  • 102
  • This would be my favourite - provided the string comes from a safe source. Otherwise, maybe a regex-based solution would be fine. – glglgl Sep 26 '11 at 12:38
  • **Moderator note:** _If you guys want to discuss the risks of using eval, please do so in chat. The comments under this answer have been removed because they degraded into noise. Removing just a few would have resulted in a broken conversation. Feel free to move it to chat, come to a resolution and then link to the transcript here._ – Tim Post Sep 27 '11 at 06:31