1

Possible Duplicate:
Converting a string that represents a list, into an actual list object.

hi,

i have a string in this format:

>>> x="(174,185)"
>>> x
'(174,185)'

how can i convert this string to list so that i can access the index 0 as 174 and index 1 as 185? i'm using Python 2.5 & Win XP. i tried a few ways but it doesn't work well. appreciate your advice. tq

>>> y=x.split(",")
>>> y
['(174', '185)']
>>> y[0]
'(174'
>>> [int(x) for x in x.split(",")]
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    [int(x) for x in x.split(",")]
ValueError: invalid literal for int() with base 10: '(174'
>>> 
Community
  • 1
  • 1
maximus
  • 89
  • 1
  • 4
  • 11

1 Answers1

3

You could try this

y=x[1:-1].split(",")

that strips off the parens before splitting

>>> x="(174,185)"
>>> map(int, x[1:-1].split(','))
[174, 185]

You could also use literal_eval if you have python2.6+

>>> from ast import literal_eval
>>> literal_eval(x)
(174, 185)
>>> 
John La Rooy
  • 295,403
  • 53
  • 369
  • 502