-1

I'm trying to convert a string to list, and I've tried split and findall but no luck. Also, I'd like to avoid for loops....

Sample:

import re

string2list = "[{u'name': u'a', u'number': u'123', u'addr': u'123 
sunshine'}, {u'name': u'b', u'number': u'456', u'addr': u'123 sunset'}]"

print re.findall('[^},]+},', string2list)
print re.split('[},]', string2list)
print re.split('[},] + }', string2list)`

Desired output is a list of the original string:

[{u'name': u'a', u'number': u'123', u'addr': u'123 
sunshine'}, {u'name': u'b', u'number': u'456', u'addr': u'123 sunset'}]

EDIT: Python version <=2.7.

EDIT 2: This almost works, just missing }:

print string2list.replace('[', '').replace(']', '').split('}')

EDIT 3: Using eval.

Simply_me
  • 2,340
  • 2
  • 14
  • 24
  • 3
    `ast.literal_eval` – kindall Aug 03 '17 at 16:58
  • WHICH version on Python? – dawg Aug 03 '17 at 17:06
  • @dawg should work from 2.4 & up. – Simply_me Aug 03 '17 at 17:07
  • @dawg I think this might need reopening. – cs95 Aug 03 '17 at 17:09
  • Probably your only choice is `eval` then but that is not at all a good choice. You could also look at an older version of [PyParsing](http://pyparsing.wikispaces.com) – dawg Aug 03 '17 at 17:10
  • @coldspeed: Reason? Every good answer to this (eval, PyParsing, JSON, regex) and for older versions is covered by the linked duplicate. – dawg Aug 03 '17 at 17:10
  • @dawg thank you for the input, I'll review `pyParsing`. In the meantime, can you please open the question to solicit other opinions? Maybe there is a regex ninja here. The answers that listed in the other question do not cover this scenario (2.4). – Simply_me Aug 03 '17 at 17:11
  • @dawg `pyParsing` isn't an option. Surely there is a way to do it natively in Python. – Simply_me Aug 03 '17 at 17:13

1 Answers1

1

The regex module is the wrong tool for this job.

You need literal_eval:

from ast import literal_eval

string2list = "[{u'name': u'a', u'number': u'123', u'addr': u'123 
sunshine'}, {u'name': u'b', u'number': u'456', u'addr': u'123 sunset'}]"

print literal_eval(string2list)
# [{u'addr': u'123sunshine', u'name': u'a', u'number': u'123'},
#  {u'addr': u'123 sunset', u'name': u'b', u'number': u'456'}]
DeepSpace
  • 65,330
  • 8
  • 79
  • 117