13

I recently found an interesting behaviour in python due to a bug in my code. Here's a simplified version of what happened:

a=[[1,2],[2,3],[3,4]]
print(str(a))
console:
"[[1,2],[2,3],[3,4]]"

Now I wondered if I could convert the String back to an Array.Is there a good way of converting a String, representing an Array with mixed datatypes( "[1,'Hello',['test','3'],True,2.532]") including integers,strings,booleans,floats and arrays back to an Array?

2
  • I hope you're aware the other question you found is for a completely different programming language, and the code in it wouldn't work at all in Python. Commented Jan 7, 2016 at 12:32
  • @ user2357112 Oh,thanks. Totally missed that. I'll remove the reference Commented Jan 7, 2016 at 12:52

2 Answers 2

21

There's always everybody's old favourite ast.literal_eval

>>> import ast
>>> x = "[1,'Hello',['test','3'],True,2.532]"
>>> y = ast.literal_eval(x)
>>> y
[1, 'Hello', ['test', '3'], True, 2.532]
>>> z = str(y)
>>> z
"[1, 'Hello', ['test', '3'], True, 2.532]"
Sign up to request clarification or add additional context in comments.

Comments

4

ast.literal_eval is better. Just to mention, this is also a way.

a=[[1,2],[2,3],[3,4]]
string_list = str(a)
original_list = eval(string_list)
print original_list == a
# True

1 Comment

I come from the future, there is no reason to use this in a situation like this.

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.