How to return a string to a list

I have a list:

ab = [1, 2, a, b, c] 

I did:

 strab = str(ab). 

So strab now a string.

I want to return this line to the list.

How can i do this?

+6
source share
3 answers

The easiest and safest way is to use ast.literal_eval() :

 import ast ab = [1, 2, 'a', 'b', 'c'] # a list strab = str(ab) # the string representation of a list strab => "[1, 2, 'a', 'b', 'c']" lst = ast.literal_eval(strab) # convert string representation back to list lst => [1, 2, 'a', 'b', 'c'] ab == lst # sanity check: are they equal? => True # of course they are! 

Note that calling eval() also works, but it is unsafe and you should not use it:

 eval(strab) => [1, 2, 'a', 'b', 'c'] 
+15
source

Use ast package:

 import ast lst = ast.literal_eval(strab) 
+6
source

In the context of setting a numpy array element with a sequence, you can use the built-in connection to bypass setting it to a string:

 str_list_obj = '-'.join(list_obj) 

and then, when necessary, split the string sequence again using the same connector (if it does not appear in the list lines):

og_list_obj = str_list_obj.split("-")

0
source

Source: https://habr.com/ru/post/949910/


All Articles