-1

Say that I have a string that looks something like this:

    x = "['345565', '1234213', '12313523', '1232346345', '1223123']"

Is there a built-in method in Python or numpy that I can use to automatically convert this into a list? I'm familiar with the eval() method and what I'm looking for is something of the same idea.

ErnestBidouille
  • 1,071
  • 4
  • 16
Onur-Andros Ozbek
  • 2,998
  • 2
  • 29
  • 78
  • At the moment, you don't have a string, you have a syntax error. Please make sure your example is a [example]. – Amadan Feb 07 '20 at 00:28
  • You need to change the left and right single-quotes to double. Then use `eval`. As posted, this isn't legal Python. – Prune Feb 07 '20 at 00:29
  • 4
    @Prune Please don't suggest `evil` when `ast.literal_eval` or `json.loads` can both handle it safely :) – Amadan Feb 07 '20 at 00:30
  • 3
    Does this answer your question? [Convert string representation of list to list](https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list) – AMC Feb 07 '20 at 01:04

3 Answers3

3

Is it ok ?

import ast
x = "['345565', '1234213', '12313523', '1232346345', '1223123']"
print(ast.literal_eval(x))
ErnestBidouille
  • 1,071
  • 4
  • 16
1

You can use the python built in library ast. ast docs

>>> import ast
>>> x = "['345565', '1234213', '12313523', '1232346345', '1223123']"
>>> x_array = ast.literal_eval(x)
>>> print(x_array)
['345565', '1234213', '12313523', '1232346345', '1223123']
>>> type(x_array)
<class 'list'>
>>> x_array
['345565', '1234213', '12313523', '1232346345', '1223123']
Phil_Miller
  • 46
  • 1
  • 4
1

You can also use the json module, but you'll have to swop the single quotes for double quotes to make it legit json:

import json
x = "['345565', '1234213', '12313523', '1232346345', '1223123']"
json.loads(x.replace("'", '"'))
Dewald Abrie
  • 1,392
  • 9
  • 21