字符串索引必须是整数,而不是python中的str错误

时间:2014-03-22 05:36:14

标签: python for-loop dictionary

我制作了以下两个词典:

# dictionary containing abbreviations for states
states = {
    'Haryana' : 'HR',
    'Uttar Pradesh' : 'UP',
    'Punjab' : 'PB',
    'Jammu and Kashmir' : 'JK',
    'Rajasthan' : 'RJ'
}

# dictionary containing the state capitals
capitals = {
    'HR' : 'Chandigarh',
    'UP' : 'Lucknow',
    'PB' : 'Chandigarh',
    'JK' : 'Srinagar',
    'RJ' : 'Jaipur'
}

然后我运行以下代码来打印州名,缩写和大写

for state, abbrev in states.items():
print "%s is abbreviated as %s and its capital is %s" % (state, abbrev, capitals[abbrev])

但是我在这一行得到了TypeError:

TypeError: string indices must be integers, not str

我认为python将大写字母作为字符串而不是字典,但拼写是相同的。

3 个答案:

答案 0 :(得分:4)

确保没有使用字符串对象覆盖capitals

>>> states = {
...     'Haryana' : 'HR',
...     'Uttar Pradesh' : 'UP',
...     'Punjab' : 'PB',
...     'Jammu and Kashmir' : 'JK',
...     'Rajasthan' : 'RJ'
... }
>>> capitals = {
...     'HR' : 'Chandigarh',
...     'UP' : 'Lucknow',
...     'PB' : 'Chandigarh',
...     'JK' : 'Srinagar',
...     'RJ' : 'Jaipur'
... }
>>>
>>> capitals = 'unexpected string' # <-------
>>>
>>> for state, abbrev in states.items():
...     print "%s is abbreviated as %s and its capital is %s" % (state, abbrev, capitals[abbrev])
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: string indices must be integers, not str

答案 1 :(得分:0)

我运行了代码,看起来很好。输出是:

Rajasthan is abbreviated as RJ and its capital is Jaipur
Punjab is abbreviated as PB and its capital is Chandigarh
Jammu and Kashmir is abbreviated as JK and its capital is Srinagar
Uttar Pradesh is abbreviated as UP and its capital is Lucknow
Haryana is abbreviated as HR and its capital is Chandigarh

答案 2 :(得分:0)

您的代码在我的计算机上运行顺畅,看起来是正确的。当您尝试将字符串用作字符串中的索引时,会出现此错误。抛出相同错误的示例:

>>> my_str = 'test'
>>> my_str['a']
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\IPython\core\interactiveshell.py", line 2735, in run_code
    exec code_obj in self.user_global_ns, self.user_ns
  File "<ipython-input-4-b93207b005cb>", line 1, in <module>
    my_str['a']
TypeError: string indices must be integers, not str

您需要重新检查capitals的定义 - 它是一个字符串,而不是字典。