string to list in python

3

Hello How can I convert string '[1,2,3,4]' to list in python having the following p>

valor_inicial = str([1,2,3])

Now I want that initial_value to convert it into a list. How can I do it?

    
asked by NEFEGAGO 05.10.2018 в 23:56
source

2 answers

3

I already managed to find 2 alternatives:

first:

valor_inicial = str([1,2,3])

import json
json.loads(valor_inicial)

second:

from ast import literal_eval

valor_inicial = str([1,2,3])
literal_eval(valor_inicial)
    
answered by 06.10.2018 / 00:10
source
0
print(map(int, "[1,2,3]".replace('[', '').replace(']', '').split(',')))
  • We remove the "[" and "]"
  • We do split() for the , to get a list
  • We only need to convert each element in a int , we do it with map(lista, int)
answered by 06.10.2018 в 00:03