TypeError:字符串索引必须是整数,而不是s

2024-04-27 03:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

    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得到的 结果={“to”:“EURO”,“rate”:0.768108149999999,“from”:“USD”}

但我有个错误:

TypeError: string indices must be integers, not str

Tags: tofromimporthttprateexchangeresulturllib2
1条回答
网友
1楼 · 发布于 2024-04-27 03:28:38

调用的结果不是字典,而是字符串:

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

[注意,虽然我认为有更好的方法来处理添加诸如fromto之类的参数,但我还是保留了url构造。还要注意,在这种情况下,将转换率转换为int是没有意义的

相关问题 更多 >