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
Release: 2024-12-20 19:39:10
Original
465 people have browsed it

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)
Copy after login

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]
Copy after login

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

['A', 'B', 'C', 'D']
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template