Python“;ValueError“;
我现在一切正常,但有个错误 控制台错误:Python“;ValueError“;,python,python-2.7,Python,Python 2.7,我现在一切正常,但有个错误 控制台错误: PS C:\Python\Artinis> python sort.py Traceback (most recent call last): File "sort.py", line 66, in <module> if int(Config.get(section, 'name')) < sn_low: ValueError: invalid literal for int() with base 10: '5DB
PS C:\Python\Artinis> python sort.py
Traceback (most recent call last):
File "sort.py", line 66, in <module>
if int(Config.get(section, 'name')) < sn_low:
ValueError: invalid literal for int() with base 10: '5DB7'
文件要长得多,但你可以理解
文件中的一些“名称”还包含章程,而不仅仅是数字。
int()只对数字进行排序
如何解决此问题?
5DB7
不是有效的十进制数。也许你的数字不是十进制而是十六进制
如果是,请告诉int()
使用不同的基址:
int(Config.get(section, 'name'), 16)
如果您在其中有名称,而不转换为任何数字,则必须显式处理这些情况。捕捉转换:
try:
number = int(Config.get(section, 'name'), 16)
except ValueError:
# handle a name that doesn't convert, perhaps set a default
number = float('inf') # a number that's guaranteed to come last
您有一个十六进制数,而不是十进制数。@Kasra:这是关于空输入值,而不是十六进制。@MartijnPieters是的,应该是这样,那么应该如何处理非数字(十六进制或其他)的名称?如果您是手工操作,您会如何对它们进行排序?将它们放在列表的底部。可能是您的配置文件出错了吗?name的值看起来应该是
222
,而不是5DB7
@Matthias:有很多设备,例如,请参阅设备26和设备27。从Device31开始,有几个名称是非数字的。@Matthia是的,名称可能是错误的,但我无法更改文件中的名称。Python必须解决这个问题,但我不知道怎么做。看到像AdBox
这样的名称,似乎把这个值当作一个数字是错误的。@DjordyWinckler:那么为什么不使用节名来进行排序呢?例如,解析出设备
后面的数字。
int(Config.get(section, 'name'), 16)
try:
number = int(Config.get(section, 'name'), 16)
except ValueError:
# handle a name that doesn't convert, perhaps set a default
number = float('inf') # a number that's guaranteed to come last