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
Release: 2024-12-28 20:51:14
Original
802 people have browsed it

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

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

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

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

will get the final result:

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template