Convert a string representation of list into list in Python

PythonServer Side ProgrammingProgramming

As python handles various data types, we will come across a situation where a list will appear in form of a string. In this article we will see how to convert a string into a list.

With strip and split

We first apply the strip method to remove the square brackets and then apply the split function. The split function with a comma as its parameter create the list from the string.

Example

 Live Demo

stringA = "[Mon, 2, Tue, 5,]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = stringA.strip('][').split(', ')
# Result and its type
print("final list", res)
print(type(res))

Output

Running the above code gives us the following result −

Given string [Mon, 2, Tue, 5,]
final list ['Mon', '2', 'Tue', '5,']

With json.loads

The json module can make a direct conversion from string to list. We just apply the function by passing the string as a parameter. We can only consider numerical elements here.

Example

 Live Demo

import json
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = json.loads(stringA)
# Result and its type
print("final list", res)
print(type(res))

Output

Running the above code gives us the following result −

Given string [21,42, 15]
final list [21, 42, 15]

With ast.literal_eval

The ast module gives us literal_eval which can directly convert the string into a list. We just supply the string as a parameter to the literal_eval method. We can only consider numerical elements here.

Example

 Live Demo

import ast
stringA = "[21,42, 15]"
# Given string
print("Given string", stringA)
print(type(stringA))
# String to list
res = ast.literal_eval(stringA)
# Result and its type
print("final list", res)
print(type(res))

Output

Running the above code gives us the following result −

Given string [21,42, 15]
final list [21, 42, 15]
raja
Published on 20-May-2020 14:11:22
Advertisements