代码之家  ›  专栏  ›  技术社区  ›  sagar

如何将列表类型更改为str?[副本]

  •  0
  • sagar  · 技术社区  · 8 年前

    我正在以以下格式从网页的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']

    2 回复  |  直到 8 年前
        1
  •  2
  •   Gsk    8 年前

    我想你在找 literal_eval :

    import ast
    
    string = '["a","b","c"]'
    
    print ast.literal_eval(string) # ['a', 'b', 'c']
    
        2
  •  1
  •   pault Tanjin    8 年前

    示例字符串中的问题是单引号。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']
    
    推荐文章