gpt4 book ai didi

python - 如何将列表类型更改为str?

转载 作者:行者123 更新时间:2023-11-30 22:18:18 25 4
gpt4 key购买 nike

我正在从网页的 html 中提取格式为

的列表
lst = '["a","b","c"]' # (type <str>)

上面的数据类型是 str ,我希望它转换为 python 列表类型 ,像这样

lst = ["a","b","c"]  #(type <list>)

我可以通过以下方式获得上述内容

lst = lst[1:-1].replace('"','').split(',')

但是由于a、b和c的实际值相当长且复杂(包含很长的html文本),所以我不能依赖上述方法。

我还尝试使用 json 模块并使用 json.loads(lst) 来完成此操作,即给出以下异常

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/json/__init__.py", line 339, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python2.7/json/decoder.py", line 364, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python2.7/json/decoder.py", line 382, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

有什么方法可以在Python中转换为列表吗?

编辑:列表的实际值为: ['reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.addedtojobcart','reqlistitem.displayjobcartactionjobdesc','reqlistitem.shareURL','reqlistitem.title','reqlistitem.shareable','reqlistitem.title','reqlistitem.contestnumber','reqlistitem.contestnumber','reqlistitem.description','reqlistitem.description','reqlistitem.primarylocation','reqlistitem.primarylocation','reqlistitem.otherlocations','reqlistitem.jobschedule','reqlistitem.jobschedule','reqlistitem.jobfield','reqlistitem.jobfield','reqlistitem.displayreferfriendaction','reqlistitem.no','reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no','reqlistitem.referjobdesc','reqlistitem.applyemailsubjectapplication','reqlistitem.applyemailjobdesc','reqlistitem.no','reqlistitem.addedtojobcart','reqlistitem.displayjobcartactionjobdesc','reqlistitem.shareURL','reqlistitem.title','reqlistitem.shareable']

最佳答案

我认为您正在寻找literal_eval:

import ast

string = '["a","b","c"]'

print ast.literal_eval(string) # ['a', 'b', 'c']

关于python - 如何将列表类型更改为str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49411263/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com