0
list_example = "['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']"

I want to convert above into this:

list_example = ['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']

I tried following: list_example = list_example.split(',') which resulted to:

["['0101612-0'",
 " '0101611-2'",
 " '0101610-4'",
 " '0101608-8'",
 " '0101607-0'",
 " '0101606-2'",
 " '0100786-3'",
 " '0100784-8'",
 " '0100783-0'",
 " '0100782-2'",
 " '0100781-4'",
 " '0100780-6'",
 " '0100779-8'",
 " '0100778-0'",
 " '0100777-2']"]

Which is messy to extract the values from.

niemmi
  • 17,113
  • 7
  • 35
  • 42

2 Answers2

5

You can use ast.literal_eval:

>>> import ast
>>> s = "['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']"
>>> ast.literal_eval(s)
['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']

You can do it with split & strip too but it's bit more complex:

>>> [x.strip('\'') for x in s.strip('[]').split(', ')]
['0101612-0', '0101611-2', '0101610-4', '0101608-8', '0101607-0', '0101606-2', '0100786-3', '0100784-8', '0100783-0', '0100782-2', '0100781-4', '0100780-6', '0100779-8', '0100778-0', '0100777-2']
niemmi
  • 17,113
  • 7
  • 35
  • 42
  • When you see a commonly-asked question, you can vote to close it as a duplicate. This helps the site maintain its quality and avoid fragmentation. – TigerhawkT3 Feb 21 '17 at 02:21
-1

The simplest (and probably most dangerous) way to do this is to use eval.

my_list = eval(list_example)

This code should return a list object full of strings. Warning: make sure the user can't input any malicious code inside of list_example!