【问题标题】:How to change type of list to str? [duplicate]如何将列表类型更改为str? [复制]
【发布时间】:2018-08-30 20:44:09
【问题描述】:

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

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

上面的数据类型是 str 我希望它转换成 python list type ,像这样

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']

【问题讨论】:

  • 您需要显示您正在使用的实际代码和数据。 json.loads(lst) 工作正常,如果 lst 如您在上面显示的那样。
  • 我已经编辑了实际值

标签: python json string list


【解决方案1】:

您的示例字符串中的问题是单引号。 JSON 标准需要双引号。

如果将单引号更改为双引号,它将起作用。一个简单的方法是使用str.replace()

import json
s = "['reqlistitem.no','reqlistitem.applyonlinejobdesc','reqlistitem.no']"
json.loads(s.replace("'", '"'))
#[u'reqlistitem.no', u'reqlistitem.applyonlinejobdesc', u'reqlistitem.no']

【讨论】:

  • 虽然这会起作用,但我有很多这样的列表,其中包含包含 ' 的其他值,因此在这些情况下替换将不起作用。
【解决方案2】:

我想你在找literal_eval:

import ast

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

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

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 2020-10-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2018-04-07
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多