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

标签 python json string list

我正在从网页的 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/

相关文章:

python openCV debayer

python - 如何在 pytest_bdd 的另一个功能文件实现中重用一个功能文件实现的步骤定义?

json - 如何在 Scala 中创建 JSON 对象?

python - 如何控制属于 Firefox 的非浏览器窗口?

python - 没有名为 'resource' 的模块在 Windows 上安装 Apache Spark

javascript - $.each 的使用有问题吗?

jquery - select_lated() 和使用 ajax 的多对多字段 (Django)

windows - 批量连接字符串很麻烦

java - 在 try block 中返回数组时遇到错误

python - MySQLdb 中执行参数类型的问题