Python 类型错误:字符串索引必须是整数,而不是 str

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15388980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 19:59:38  来源:igfitidea点击:

TypeError: string indices must be integers, not str

pythondictionary

提问by imoum

    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) 

this what i got with print presult = {"to": "EURO", "rate": 0.76810814999999999, "from": "USD"}

这就是我得到的print p结果 = {"to": "EURO", "rate": 0.76810814999999999, "from": "USD"}

but I have the error:

但我有错误:

TypeError: string indices must be integers, not str

回答by DSM

The result of your .read()call isn't a dictionary, it's a string:

您的.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'>

It looks like the result is a JSON-encoded dict, and so you can use something like

看起来结果是一个 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'>

[Note that I left your url construction alone, although I think there are better ways to handle adding parameters like fromand to. Also note that under the circumstances it doesn't make sense to convert the conversion rate into an int.]

[请注意,我没有考虑您的 url 构造,尽管我认为有更好的方法来处理添加fromto. 另请注意,在这种情况下,将转换率转换为int.]是没有意义的。]