import urllib2
currency = 'EURO'
req = urllib2.urlopen(' http://rate-exchange.appspot.com/currency?from=USD&to='+ currency +'')
result = req.read()
print p
p = result["rate"]
print int(p)
这是我print p
所得到的
result = {“to”:“EURO”,“rate”:0.76810814999999999,“from”:“USD”}
但我有错误:
TypeError: string indices must be integers, not str
答案 0 :(得分:10)
.read()
来电的结果不是字典,而是字符串:
>>> import urllib2
>>> currency = "EURO"
>>> req = urllib2.urlopen('http://rate-exchange.appspot.com/currency?from=USD&to='+ currency +'')
>>> result = req.read()
>>> result
'{"to": "EURO", "rate": 0.76810814999999999, "from": "USD"}'
>>> type(result)
<type 'str'>
看起来结果是JSON编码的dict,所以你可以使用像
这样的东西>>> import json, urllib2
>>> currency = "EURO"
>>> url = "http://rate-exchange.appspot.com/currency?from=USD&to=" + currency
>>> response = urllib2.urlopen(url)
>>> result = json.load(response)
>>> result
{u'to': u'EURO', u'rate': 0.76810815, u'from': u'USD'}
>>> type(result)
<type 'dict'>
>>> result["rate"]
0.76810815
>>> type(result["rate"])
<type 'float'>
[请注意,我单独留下了您的网址结构,但我认为有更好的方法来处理添加from
和to
等参数。另请注意,在这种情况下,将转换率转换为int
。