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,750
  • 8
  • 45
  • 80

2 Answers2

3

One should use ast.literal_eval:

>>> import ast
>>> ast.literal_eval('[1,2,3]')
[1, 2, 3]
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
alko
  • 46,136
  • 12
  • 94
  • 102
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,072
  • 7
  • 14