1

I have a string separated by comma(,) which contains list, integer,boolean and string. How to convert this to a list. For example,

s= "[{'Name':'key','Values':['data']}],6,True,'somestring'"

I want to convert this to list as below in Python(3.5v)

[[{'Name':'key','Values':['data']}],6,True,'somestring']

The problem here is, when i tried to split it based on comma, the items inside list get divided. Please help.

rose
  • 31
  • 5

2 Answers2

0

Use ast.literal_eval:

import ast
s= "[{'Name':'key','Values':['data']}],6,True,'somestring'"
print(list(ast.literal_eval(s)))

# [[{'Name': 'key', 'Values': ['data']}], 6, True, 'somestring']
Austin
  • 25,759
  • 4
  • 25
  • 48
  • If there is only a single value as input either integer or boolean, this is throwing error `>>> s= "6" >>> b=list(ast.literal_eval(s)) Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not iterable >>>` and `>>> s="True" >>> b=list(ast.literal_eval(s)) Traceback (most recent call last): File "", line 1, in TypeError: 'bool' object is not iterable >>>` – rose Apr 26 '18 at 13:23
  • and with single string too: `>>> s="somerolename" >>> ast.literal_eval(s) Traceback (most recent call last): File "", line 1, in File "C:\Python 3.5.4\lib\ast.py", line 84, in literal_eval return _convert(node_or_string) File "C:\Python 3.5.4\lib\ast.py", line 83, in _convert raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: <_ast.Name object at 0x01065CD0>` – rose Apr 26 '18 at 13:34
  • See https://stackoverflow.com/questions/47710393/malformed-string-while-using-ast-literal-eval and https://stackoverflow.com/questions/17630323/typeerrorbool-object-is-not-iterable-when-trying-to-return-a-boolean and – Austin Apr 26 '18 at 14:41
0

You can use literal_eval method from ast module

s="[{'Name':'key','Values':['data']}],6,True,'somestring'"
list(ast.literal_eval(s))

Out

[[{'Name': 'key', 'Values': ['data']}], 6, True, 'somestring']
Roushan
  • 4,074
  • 3
  • 21
  • 38