1

So I'm having an issue where when I read in info from an xml file. The data it reads in is supposed to be a list of numbers but when I read it in, it comes as a string. Is there a way to read xml data as a list or a way to convert a string to a list.

Eg I get the data from the xml as say [1.0, 2.0, 3.0, 4.0, 5.0] and if I check the type it says its a string, ie the whole thing is a string including the brackets and the comma.

Can't wrap my head around how to convert this back to a list of numbers

5
  • [float(x) for x in mystring.lstrip('[').rstrip(']').strip().split(',')] Commented Dec 3, 2017 at 1:18
  • @AK47 What a magnificent one-liner! Not very helpful for a beginner though... Commented Dec 3, 2017 at 1:25
  • @AK47 Yes, that's a good method, worth an upvote (I never even thought about eval()! Ususally I avoid it like the plague, but this might be a real application for it!) Commented Dec 3, 2017 at 1:27
  • [float(x) for x in mystring.lstrip('[').rstrip(']').strip().split(',')] – AK47 38 mins ago This worked out brilliantly! Thank you!! Commented Dec 3, 2017 at 1:57
  • @dege the eval() command is cleaner and works in python2 and python3 Commented Dec 3, 2017 at 18:06

2 Answers 2

4

You can use eval() if you want to convert your string to a list of floats

>>> string = '[1.0, 2.0, 3.0]'

>>> print(type(string))
<type 'str'>

>>> mylist = eval(string)

>>> print(type(mylist))
<type 'list'>

>>> print([type(x) for x in mylist])
[<type 'float'>, <type 'float'>, <type 'float'>]

>>> print(mylist)
[1.0, 2.0, 3.0]
Sign up to request clarification or add additional context in comments.

4 Comments

Ah forgot to mention I'm trying this in python. So the eval command doesn't work as it's a keyword in maya's version of python libraries
eval() is a builtin for both python2 and python3
yeah buy maya has it's version of eval() as well so it overwrites python's eval() unfortunately.
I stand corrected... eval() does work and it is a lot easier... noob mistake of calling maya's version of eval() as maya.cmds.eval() instead of python eval()... I need coffee
2

For this, you would use the str.split() builtin method.

Set x = "[1.0, 2.0, 3.0, 4.0, 5.0]"

First of all, get rid of the square brackets around the string:

x = x[1:-1] (x is now "1.0, 2.0, 3.0, 4.0, 5.0", a long string)

Then, split the string to form a list of strings:

x = x.split(',') (x is now ["1.0", "2.0", "3.0", "4.0", "5.0"], a list of strings)

Then, convert all of these strings into floats (as I assume you want that):

x = [float(i) for i in x] (x is now [1.0, 2.0, 3.0, 4.0, 5.0], a list of floats)

Comments

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.