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

-4 投票
1 回答
23572 浏览
提问于 2025-04-17 18:57
    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) 
TypeError: string indices must be integers, not str

这是我用 print p 得到的结果:

结果是一个字典,内容是 {"to": "EURO", "rate": 0.76810814999999999, "from": "USD"}。

但是我遇到了一个错误:

1 个回答

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编码的字典,所以你可以使用类似下面的方式来处理:

>>> 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 这样的参数。另外,在这种情况下,把汇率转换成 int 是没有意义的。]

撰写回答