简体   繁体   English

Python 字符串索引必须是整数

[英]Python string indices must be integers

I'm reading a Dictionary from an API which has a field called 'price'.我正在阅读来自 API 的字典,其中有一个名为“价格”的字段。

I'm reading it fine for a while (so, the code works) until I get to a point I get the error message: string indices must be integers.我正在阅读它一段时间(因此,代码有效),直到我到达某个点我收到错误消息:字符串索引必须是整数。

That breaks my code.那破坏了我的代码。

So, I would like to find a way to skip it (ignore it) when this happens, and continue with the code.所以,我想找到一种方法在发生这种情况时跳过它(忽略它),并继续代码。 And just print something out so I know something happened.只需打印一些东西,这样我就知道发生了什么事。

So, far I don't manage to see what number is causing this error.所以,到目前为止,我还没有设法看到是什么数字导致了这个错误。

If I test this by itself, it works fine.如果我自己测试它,它工作正常。

fill = {'price': 0.00002781 }
price = fill['price'] # OUTPUT: string indices must be integers
print(price)

I've tried many things:我尝试了很多事情:

from decimal import Decimal
price = decimal(fill['price'])

also:还:

price = int(fill['price']) # but it's not really an int

and:和:

price = float(fill['price']) # but sometimes it's a very big float so I need decimal

string indices must be integers tells you that the type of fill during runtime at some point is a str instead of Dict . string indices must be integers告诉您在运行时的某个时刻fill的类型是str而不是Dict I suggest that you add type checking or assertion to your program to make sure fill is of the expected type.我建议您在程序中添加类型检查或断言,以确保fill是预期的类型。

It seems that what you get from the API is not exactly what you expect:看起来你从 API 得到的并不完全是你所期望的:

The variable fill is a string (at least at the time you get the error).变量fill是一个字符串(至少在您收到错误时是这样)。 As strings can't have string indices (like dictionaries can) you get the TypeError exception.由于字符串不能有字符串索引(像字典一样),你会得到TypeError异常。

To handle the exception and troubleshoot it, you can use try-except , like so:要处理异常并对其进行故障排除,您可以使用try-except ,如下所示:

try:
    price = fill['price']
except TypeError as e:
    print(f"fill: {fill}, exception: {str(e)}")

This way, when there is an issue, the fill value will be printed as well as the exception.这样,当出现问题时,将打印fill值以及异常。

If you want to just ignore it you could use try and except blocks.如果你只想忽略它,你可以使用 try 和 except 块。

try:
  price = fill['price']
except Exception as e:
  print(f"Error reading the price. Error: {e}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM