【问题标题】:TypeError: string indices must be integers, not str [closed]TypeError:字符串索引必须是整数,而不是 str [关闭]
【发布时间】:2013-03-13 15:04:52
【问题描述】:
    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.76810814999999999,“from”:“USD”}

但我有错误:

TypeError: string indices must be integers, not str

【问题讨论】:

  • 不,不是你没有的代码。您发布的示例确实 not 给出了错误。您可能在代码中的某个地方做了一个result = somestringvalue,而您错过了。
  • 该代码在 Python 2.7 中对我来说很好
  • 什么版本的python?
  • @ValekHalfHeart:在 Python 3 中,该代码将引发语法错误(因为 print 是一个函数)。在 Python 2 中,代码 Just Works。在这里要求一个版本没有意义。
  • 是的,确认所有所说的:print int(p) 打印 0,正确。那是你得到的所有代码sn-p吗?

标签: python dictionary


【解决方案1】:

.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 之类的参数,但我没有考虑您的 url 构造。另请注意,在这种情况下,将转化率转换为int 是没有意义的。]

【讨论】:

    猜你喜欢
    • 2013-12-16
    • 1970-01-01
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多