-2

I have data coming from DB in the form of string.

e.g = ['foo1', 'bar1', 'foo2', 'bar2'] and type is class 'str'

I want to convert it into a python list.

>>> db_string = ['foo1', 'bar1', 'foo2', 'bar2']
>>> db_string.strip('][').split(', ')
["'foo1'", "'bar1'", "'foo2'", "'bar2'"]

I want much better solution.

RoadRunner
  • 23,173
  • 5
  • 28
  • 59
rahul.m
  • 4,695
  • 3
  • 15
  • 39
  • 1
    Your code is incorrect. You cannot apply either `strip` or `split` to an object of type `list`, like you do in the example. Even the assignment in the *e.g.* line is incorrect, since the value is a list, but you claim it is a string. – Amitai Irron May 11 '20 at 06:51
  • @c.grey - If you can write the whole data to file (e.g db_strings.py) insted the stdout. then you can import it in python. no need for conversions. if this possible its the best solution you can get. It works for me and its cool solution. try it! – nor May 11 '20 at 07:01
  • You should *fix* whatever is generating strings like this. Use an actual text-based serialization format, don't just use the `str` representation, that isn't what it's meant for – juanpa.arrivillaga May 11 '20 at 07:09

2 Answers2

4

Use ast.literal_eval:

>>> from ast import literal_eval
>>> db_string = "['foo1', 'bar1', 'foo2', 'bar2']"
>>> result = literal_eval(db_string)
>>> result
['foo1', 'bar1', 'foo2', 'bar2']
>>> type(result)
<class 'list'>
RoadRunner
  • 23,173
  • 5
  • 28
  • 59
4

If you replace the single quotes with double quotes, your string becomes valid JSON and you can use json.loads:

import json

db_string = "['foo1', 'bar1', 'foo2', 'bar2']"

lst = json.loads(db_string.replace("'", '"'))
print(lst)

Output:

['foo1', 'bar1', 'foo2', 'bar2']
Nick
  • 118,076
  • 20
  • 42
  • 73