Python | Convert list to string

Examples :

  Input:  "[0, 2, 9, 4, 8]"  Output:  [0, 2, 9, 4, 8]  Input:  "[` x`, `y`,` z`] " Output:  [` x`, ` y`, `z`] 

Approach # 1: Python eval()

eval () method parses the expression passed to this method and executes the Python expression (code) in the program. Here it takes a quoted list as an expression and runs it, and finally returns a list.

# Python3 conversion program
# a list enclosed in a string for the list

 

def convert (lst):

return eval (lst)

 
# Driver code

lst = "[0, 2, 9, 4, 8]"

print (convert (lst))

Exit :

[0, 2, 9, 4, 8]

Approach # 2 Using literal_eval()

The literal_eval () function works the same as eval () with the only difference that it throws an exception if the input is not a valid Python data type the code will not execute.

# Python3 conversion program
# a list enclosed in a string for a list

from ast import literal_eval

 

def convert (lst):

return literal_eval (lst)

  
# Driver code

lst = " [0, 2, 9, 4, 8] "

print (convert (lst))

Output:

 [0, 2, 9, 4, 8] 

Approach # 3 Using json.loads ( )

# Python3 conversion program
# list enclosed in a string for list

from json import loads

 

def convert (lst):

return loads (lst)

  
# Driver code

lst = "[0, 2, 9, 4, 8]"

print ( convert (lst))

Exit:

 [0, 2, 9, 4, 8]