-3

How can I convert in Python 3.x string like this: {str} '[21,2,14]' into int array like this: {list: 3} [21,2,14] ?

  • 1
    you can use ``json``, you can use ``ast``, or you can write your own parser – Mike Scotty Feb 12 '21 at 14:35
  • 1
    Duplicate https://stackoverflow.com/questions/1894269/how-to-convert-string-representation-of-list-to-a-list – Epsi95 Feb 12 '21 at 14:35
  • Does this answer your question? [How to convert comma-delimited string to list in Python?](https://stackoverflow.com/questions/7844118/how-to-convert-comma-delimited-string-to-list-in-python) – pieca Feb 12 '21 at 14:36
  • 1
    Did you remember to [search](https://stackoverflow.com/search) before posting? This is a pretty standard task, with many examples online already. – costaparas Feb 12 '21 at 14:36

2 Answers2

0

Use ast.literal_eval, a safer alternative to eval:

import ast
print(ast.literal_eval('[21,2,14]'))
# [21, 2, 14]
Timur Shtatland
  • 7,599
  • 2
  • 20
  • 30
0

I like ast for tasks like this - https://docs.python.org/3/library/ast.html

import ast 
input_values = '[21,2,14]'
eval_input = ast.literal_eval(input_values)

outputs [21, 2, 14]

Joseph Lane
  • 141
  • 2
  • 5