【发布时间】:2020-10-30 07:29:52
【问题描述】:
我在下面有一个字符串列表我想变成一个列表
import json
import ast
s = "['https://i.ebayimg.com/images/g/PWMAAOSw4MdfmPuu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/mFwAAOSw-8xfPMyu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/inUAAOSwIftfPMyx/s-l1000.jpg', 'https://i.ebayimg.com/images/g/8WcAAOSw~dxfPMy~/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lRAAAOSwqSBfPMy9/s-l1000.jpg', 'https://i.ebayimg.com/images/g/1akAAOSwQJBfPMzB/s-l1000.jpg', 'https://i.ebayimg.com/images/g/EQYAAOSwPZNfPMzE/s-l1000.jpg', 'https://i.ebayimg.com/images/g/YfAAAOSwQDFfPMzR/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rqwAAOSwCoJfPMzP/s-l1000.jpg', 'https://i.ebayimg.com/images/g/fJcAAOSwn9VfPMzT/s-l1000.jpg', 'https://i.ebayimg.com/images/g/QN8AAOSwfo1fPMzV/s-l1000.jpg', 'https://i.ebayimg.com/images/g/KusAAOSwYEdfPMze/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lIMAAOSw2rNfPMzb/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rKYAAOSwHKZfPMzg/s-l1000.jpg', 'https://i.ebayimg.com/images/g/krgAAOSwpAZfPMzh/s-l1000.jpg']"
m = json.loads(s)
虽然 json.loads() 出错,但 ast 可以正常工作
import json
import ast
s = "['https://i.ebayimg.com/images/g/PWMAAOSw4MdfmPuu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/mFwAAOSw-8xfPMyu/s-l1000.jpg', 'https://i.ebayimg.com/images/g/inUAAOSwIftfPMyx/s-l1000.jpg', 'https://i.ebayimg.com/images/g/8WcAAOSw~dxfPMy~/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lRAAAOSwqSBfPMy9/s-l1000.jpg', 'https://i.ebayimg.com/images/g/1akAAOSwQJBfPMzB/s-l1000.jpg', 'https://i.ebayimg.com/images/g/EQYAAOSwPZNfPMzE/s-l1000.jpg', 'https://i.ebayimg.com/images/g/YfAAAOSwQDFfPMzR/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rqwAAOSwCoJfPMzP/s-l1000.jpg', 'https://i.ebayimg.com/images/g/fJcAAOSwn9VfPMzT/s-l1000.jpg', 'https://i.ebayimg.com/images/g/QN8AAOSwfo1fPMzV/s-l1000.jpg', 'https://i.ebayimg.com/images/g/KusAAOSwYEdfPMze/s-l1000.jpg', 'https://i.ebayimg.com/images/g/lIMAAOSw2rNfPMzb/s-l1000.jpg', 'https://i.ebayimg.com/images/g/rKYAAOSwHKZfPMzg/s-l1000.jpg', 'https://i.ebayimg.com/images/g/krgAAOSwpAZfPMzh/s-l1000.jpg']"
m=ast.literal_eval(s)
print(type(m))
print(m)
但是我以前成功使用json.loads()转换的字符串列表,为什么它在这个字符串列表上不起作用?
【问题讨论】:
-
这不是有效的 JSON。
ast.literal_eval解析 Python 语法的一个子集;json.loads解析 JSON。没有理由期望两者之间有任何联系。
标签: python python-3.x string list