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)

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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.

2 Comments

This would be my favourite - provided the string comes from a safe source. Otherwise, maybe a regex-based solution would be fine.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.