2

I am receving a string through a socket like so

"['[0,0,0]','[0,0,0]']"

I would like to convert it back to a array. I have tried using

received.split(",")

however it splits up the arrays inside the array.

How would I go about converting the string to an array?

8
  • did you tried with eval() ? Commented Aug 24, 2013 at 8:25
  • What exactly do you want as the output? You already have a string... Commented Aug 24, 2013 at 8:27
  • sorry edited my question i meant array Commented Aug 24, 2013 at 9:25
  • I recommend using JSON and then using a JSON parser. Keeps you away from eval, but gets you what you want. Commented Aug 24, 2013 at 10:02
  • @GrijeshChauhan never eval data from the network. Though the answer below seems to say there is a version of eval that is safe, as it cannot eval code. Commented Aug 24, 2013 at 10:03

1 Answer 1

5
>>> import ast
>>> s = "['[0,0,0]','[0,0,0]']"
>>> s = ast.literal_eval(s)
>>> s
['[0,0,0]', '[0,0,0]']
>>> s = [ast.literal_eval(sub) for sub in s]
>>> s
[[0, 0, 0], [0, 0, 0]] 

Using literal_eval is safer than eval. From the docs:

31.2. ast — Abstract Syntax Trees¶

ast.literal_eval(node_or_string)

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python expressions from untrusted sources without the need to parse the values oneself.

Sign up to request clarification or add additional context in comments.

1 Comment

Add documentation link: 31.2. ast — Abstract Syntax Trees¶ and link that suggests preference of your technique over simple eval() given by me: here is the link: stackoverflow.com/questions/15197673/….

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.