0

I am not sure if there is a solution for this on stack overflow; so apologies if this is a duplicate.

There are number of ways of converting the string:

s = '[1, 2, 3]'

to a list

t = [1, 2, 3]

but I am looking for the most straightforward pythonic way of doing this. Also, performance matters.

p0lAris
  • 4,610
  • 7
  • 43
  • 79

2 Answers2

3

One should use ast.literal_eval:

>>> import ast
>>> ast.literal_eval('[1,2,3]')
[1, 2, 3]
thefourtheye
  • 221,210
  • 51
  • 432
  • 478
alko
  • 43,000
  • 9
  • 91
  • 100
1

Why never use json library.

import json
# convert str to list 
t = json.loads(s)

# back to string
s2 = json.dumps(t)
crazyzubr
  • 1,042
  • 7
  • 11