Convert string enclosed list to list in Python

PythonServer Side ProgrammingProgramming

We may sometime get data which contains strings but the structure of the data inside the stream is a Python list. In this article we will convert string enclosed list to an actual Python list which can be further used in data manipulation.

With eval

We know the eval function will give us the actual result which is supplied to it as parameter. So so we supplied the given string to the eval function and get back the Python list.

Example

 Live Demo

stringA = "['Mon', 2,'Tue', 4, 'Wed',3]"
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using eval
res = eval(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

Output

Running the above code gives us the following result −

Given string :
['Mon', 2,'Tue', 4, 'Wed',3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

With ast.literal_eval

In this approach, we take the estimate and use the literal_eval function by giving it the string as a parameter. It gives back the Python list.

Example

 Live Demo

import ast
stringA = "['Mon', 2,'Tue', 4, 'Wed',3]"
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using literal_eval
res = ast.literal_eval(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

Output

Running the above code gives us the following result −

Given string :
['Mon', 2,'Tue', 4, 'Wed',3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

With json.loads

The loads function injection module can do a similar conversion where the string is evaluated and actual Python list is generated.

Example

 Live Demo

import json
stringA = '["Mon", 2,"Tue", 4, "Wed",3]'
# Given string
print("Given string : \n",stringA)
# Type check
print(type(stringA))
# using loads
res = json.loads(stringA)
# Result
print("The converted list : \n",res)
# Type check
print(type(res))

Output

Running the above code gives us the following result −

Given string :
["Mon", 2,"Tue", 4, "Wed",3]

The converted list :
['Mon', 2, 'Tue', 4, 'Wed', 3]

raja
Published on 04-Jun-2020 11:11:07
Advertisements