Home >Backend Development >Python Tutorial >How to Easily Convert a String Representation of a List to a Python List?
Question:
How to convert something like the following Convert string representation of list to list?
x = '[ "A","B","C" , " D"]'
Even if the user adds spaces between commas and within quotes, it needs to be handled correctly and converted to:
x = ["A", "B", "C", "D"]
Answer:
This conversion can be easily accomplished using the ast.literal_eval() function.
import ast x = '[ "A","B","C" , " D"]' x = ast.literal_eval(x)
ast.literal_eval() function:
In order to further eliminate the impact of spaces, you can use list parsing:
x = [n.strip() for n in x]
will get the final result:
['A', 'B', 'C', 'D']
The above is the detailed content of How to Easily Convert a String Representation of a List to a Python List?. For more information, please follow other related articles on the PHP Chinese website!