Home >Backend Development >Python Tutorial >How Can I Efficiently Convert a String Representation of a List into a Python List?

How Can I Efficiently Convert a String Representation of a List into a Python List?

DDD
DDDOriginal
2024-12-20 19:39:10466browse

How Can I Efficiently Convert a String Representation of a List into a Python List?

Converting a String Representation of a List into a List

To convert a string that represents a list into an actual list, we need to handle potential spaces within the string. While custom code using strip() and split() can be cumbersome, Python offers a simpler solution.

Solution

Utilizing the ast.literal_eval() function, we can parse the string and convert it into a list:

import ast

x = '[ "A","B","C" , " D"]'
x = ast.literal_eval(x)

After parsing, we may encounter extra spaces within the list elements. To remove these, we can use a list comprehension:

x = [n.strip() for n in x]

This will result in a clean list without any extra spaces:

['A', 'B', 'C', 'D']

ast.literal_eval()

The ast.literal_eval() function evaluates a string or expression node that contains only simple Python literals, such as:

  • Strings
  • Bytes
  • Numbers
  • Tuples
  • Lists
  • Dicts
  • Sets
  • Booleans
  • None
  • Ellipsis

This function is an efficient and convenient way to parse string representations of data structures in Python.

The above is the detailed content of How Can I Efficiently Convert a String Representation of a List into a Python List?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn