将字符串列表转换为正确的列表

huangapple go评论74阅读模式
英文:

Convert a string of list to a proper list

问题

The code you provided appears to be attempting to convert a string containing a list of strings into an actual list of strings. The mistake you are making is that the string a contains HTML-encoded double quotes (") instead of regular double quotes ("). You can use the html module to decode the HTML entities and then use ast.literal_eval to parse the list correctly. Here's the corrected code:

import ast
import html

a = """\"[\"123456789\",\"987654321\"]\""""
decoded_a = html.unescape(a)
lst = ast.literal_eval(decoded_a)

This will give you the expected output: ['123456789', '987654321'].

英文:

I have the following:

a = """\"[""123456789"",""987654321""]\""""

I am trying to convert that to a list of strings. I've tried the following:

lst = ast.literal_eval(a)

but this returns all the characters as an individual string. What is the mistake I am doing?

The expected output: ["123456789", "987654321"]

答案1

得分: 1

你可以尝试两次使用 literal_eval 来获取一个整数列表,然后将每个整数映射为字符串,如下所示:

from ast import literal_eval as le
lst = le(le(a))
lst = list(map(str, lst))

lst 现在将变成 ['123456789', '987654321']

英文:

You can try literal_eval twice to get a list of integers and then map each integer to strings like this :

from ast import literal_eval as le
lst = le(le(a))
lst = list(map(str, lst))

lst would now become ['123456789', '987654321']

huangapple
  • 本文由 发表于 2023年4月17日 23:01:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76036558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定