python把字符串转换成列表
阿神
阿神 2017-04-17 15:29:57
0
5
662
python{'title': u'第一条新闻标题', 'description': u'第一条新闻描述,这条新闻没有预览图','picurl':u'http://img1.imgtn.bdimg.com/it/u=1779112580,3658566843&fm=15&gp=0.jpg', 'url':u'http://www.google.com.hk/',},{'title': u'第二条新闻标题, 这条新闻无描述',   'picurl':u'http://img1.imgtn.bdimg.com/it/u=599056397,2868563288&fm=21&gp=0.jpg','url':u'http://www.github.com/',},{'title': u'第三条新闻标题','description': u'第三条新闻描述','picurl':u'http://img1.imgtn.bdimg.com/it/u=599056397,2868563288&fm=21&gp=0.jpg','url': u'http://www.v2ex.com/',}

字符串如这样(这是字符串不是字典),我想把他转换成列表

python[
    {
        'title': u'第一条新闻标题',
        'description': u'第一条新闻描述,这条新闻没有预览图',
        'picurl':u'http://img1.imgtn.bdimg.com/it/u=1779112580,3658566843&fm=15&gp=0.jpg',
        'url':u'http://www.google.com.hk/',
    }, 
    {
        'title': u'第二条新闻标题, 这条新闻无描述',
        'picurl':u'http://img1.imgtn.bdimg.com/it/u=599056397,2868563288&fm=21&gp=0.jpg',
        'url':u'http://www.github.com/',
    },
    {
        'title': u'第三条新闻标题',
        'description': u'第三条新闻描述',
        'picurl': u'http://img1.imgtn.bdimg.com/it/u=599056397,2868563288&fm=21&gp=0.jpg',
        'url': u'http://www.v2ex.com/',
    }
]

直接 list()是不行的,应该怎么办,用正则匹配出来吗

阿神
阿神

闭关修行中......

reply all(5)
黄舟
>>> s = "{'a':1},{'b':2}"
>>> list(eval(s))
[{'a': 1}, {'b': 2}]
巴扎黑

By observation, your string looks like a Json string. It is now popular to use json as a format for data transmission. I wonder if the two symbols [ and ] were missed in the source code of the post.

Even if this is the case, you can also consider manually completing it into a json string, and then using the json library loads to convert it into a list.

pythonimport json

s = "[{}, {}, ...{}]" # 补全为json字符串的格式,大概就是 python 字典字面形式的字符串。
data = json.loads(s)
巴扎黑
pythons = "[{'t':u'dd'}]"
print eval(s)
刘奇

eval('['+s+']')

小葫芦

If the string is eval directly, it may cause loopholes if the string is controllable by the user. It is recommended to use json parsing.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!