-1

I'm receiving a message that is a list of lists but is recognized as a string in Python. I can't figure out how to get Python to interpret the string as a list of lists, is there a simple way to do this? An example of the format I'm dealing with is shown below:

>>soc = '[["hello","world"],["foo","bar"]]'
>>type(soc)
<type 'str'>

I want to convert this string into an unaltered list of lists:

>>soc
[["hello","world"],["foo","bar"]]
>>type(soc)
<type 'list'>

I'd appreciate any help offered, thanks!

2

3 Answers 3

0

Use ast.literal_eval:

import ast

soc = '[["hello","world"],["foo","bar"]]'

ast.literal_eval(soc)

# [['hello', 'world'], ['foo', 'bar']]
Sign up to request clarification or add additional context in comments.

Comments

0

You could use json.loads

>>> import json
>>> json.loads(soc)
[['hello', 'world'], ['foo', 'bar']]

Comments

0

why not the builtin eval function

soc = eval('[["hello","world"],["foo","bar"]]')
type(soc)
Out[5]: list

soc
Out[6]: [['hello', 'world'], ['foo', 'bar']]

soc[1][0]
Out[7]: 'foo'

and now for the expected objections about 'safety'...

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.