英文:
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']
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论