Home >Backend Development >Python Tutorial >How to Easily Convert a String Representation of a List to a Python List?

How to Easily Convert a String Representation of a List to a Python List?

Susan Sarandon
Susan SarandonOriginal
2024-12-28 20:51:14791browse

How to Easily Convert a String Representation of a List to a Python List?

Converting a String Representation of a List to a List with Ease

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:

  • Evaluates an expression node or a string containing only a Python literal or container display.
  • The provided string or node can only contain the following Python literal structures: String, Byte, Number, Tuple, List, Dictionary, Set, Boolean, None and Ellipsis.
  • can be used to evaluate strings containing Python values ​​without parsing the values ​​yourself. It cannot evaluate arbitrarily complex expressions, such as those involving operators or indexes.

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!

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