3

I have a string:

s= "[7, 9, 41, [32, 67]]"

and I need to convert that string into a list:

l= [7, 9, 41, [32, 67]]

the problem is, when I use list(s) I get this:

['[', '7', ',', ' ', '9', ',', ' ', '4', '1', ',', ' ', '[', '3', '2', ',', ' ', '6', '7', ']', ']']

I am using python 3.2

2
  • What format is the string in? JSON? Python? Other? Commented Sep 16, 2012 at 14:27
  • 1
    The reason you get what you do is that strings are iterable, with their characters as the entries. If you pass list an iterable, it will give you a list containing the entries from the iterable. Commented Sep 16, 2012 at 14:28

6 Answers 6

4

You can do exactly what you asked for by using ast.literal_eval():

>>> ast.literal_eval("[7, 9, 41, [32, 67]]")
[7, 9, 41, [32, 67]]

However, you probably want to use a sane serialisation format like JSON in the first place, instead of relying on the string representation of Python objects. (As a side note, the string you have might even be JSON, since the JSON representation of this particular object would look identical to the Python string representation. Since you did not mention JSON, I'm assuming this is not what you used to get this string.)

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

2 Comments

I am trying to do this because I'm sending the data as a string over a socket, is there a better way?
@ParkerHoyes: Yes, just any proper serialisation is better. Have a look at Python's json and pickle modules, to name two.
2

Use the ast module, it has a handy .literal_eval() function:

import ast

l = ast.literal_eval(s)

On the python prompt:

>>> import ast
>>> s= "[7, 9, 41, [32, 67]]"
>>> ast.literal_eval(s)
[7, 9, 41, [32, 67]]

Comments

2

You want to use ast.literal_eval:

import ast
s= "[7, 9, 41, [32, 67]]"
print ast.literal_eval(s)
# [7, 9, 41, [32, 67]]

Comments

0

Use: package ast: function : literal_eval(node_or_string)

http://docs.python.org/library/ast.html#module-ast

Comments

0

It is another answer, But I don't suggest you.Because exec is dangerous.

>>> s= "[7, 9, 41, [32, 67]]"
>>> try:
...   exec 'l = ' + s
...   l
... except Exception as e:
...   e
[7, 9, 41, [32, 67]]

Comments

0

why not use eval()?

>>> s = "[7, 9, 41, [32, 67]]"
>>> eval(s)
[7, 9, 41, [32, 67]]

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.