首页 > 解决方案 > 为什么 int("0xff",16) 计算但 int("hello", 16) 不计算?

问题描述

如果这是一个愚蠢的问题,请原谅我。我目前正处于通过 Skillsoft 课程学习 Python 的初级阶段。讲师使用的示例之一是:int("0xff",16)它计算并打印了 255。

我只是感到困惑,因为虽然我知道 0xff 是“整数值为 255 的十六进制数 FF”(感谢 Google),但我不明白“0xff”如何不被视为字符串由于引号. 当我尝试时int("hello",16),我遇到了:

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    int("hello", 16)
ValueError: invalid literal for int() with base 16: 'hello'

当“0xff”和“hello”都是字符串时,如何int("0xff",16)计算但不能计算?int("hello",16)

标签: python-3.xstringintegerint

解决方案


因为"0xff"是表示十六进制数(基数16)的字符串,十六进制数的数字范围从0to9和 from ato f"hello"has "h""l""o",它们都不是有效的十六进制数字。

"0x"in只是用来指定这"0xff"是一个十六进制字符串,实际数字只是"ff"( int("ff", 16) ==> 255)。

要了解为什么允许使用字符串,请考虑17-base 数字系统 (0-9和) 中的一个数字,a-g您将如何使用此系统中的数字,.int"gg"int("gg", 17)

您可以使用intwith "hello",但只能使用大于或等于的基数25(因为10 + ord(max("hello")) - 97 + 1 == 25),int("hello", 25) ==> 6873049


推荐阅读