RicardoGarcia RicardoGarcia - 10 months ago 51
Python Question

How can I convert a vector in string form to tuple form with each vector component being a tuple element?

I'm writing a Python script to parse an XML file. When I get to the following part of the XML file,

(1.00000000000000, 0.000000000000000E+000)

the script uses the following to parse the text

H1 = H.find('H.1')
tokens = H1.text.split()

This produces a list named tokens with the single string element '(1.00000000000000,0.000000000000000E+000)'. How can I make it so that what is produced is a tuple with first element 1.00000000000000 and second element 0.000000000000000E+000? Or, at least, how can I convert the vector from string form to two-element tuple form?

Answer Source

You can use literal_eval from ast:

>>> s = '(1.00000000000000,0.000000000000000E+000)'
>>> from ast import literal_eval
>>> t = literal_eval(s)
>>> t
(1.0, 0.0)
>>> type(t[0])
<type 'float'>
>>> print(type(t))
<type 'tuple'>