开发者

How to convert a string to tuple

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)


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.


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜