为什么 int("0xff",16) 计算但 int("hello", 16) 不计算?

Why does int("0xff",16) compute but, say, int("hello", 16) not?

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

我只是感到困惑,因为虽然我知道 0xff 是 "the hexcidecimal number FF which has an integer value of 255"(谢谢,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)

因为"0xff"是一个表示十六进制数的字符串(基数16),而十六进制数的位数范围从09,从af, "hello""h", "l", 和 "o", none 其中是有效的十六进制数字.

"0xff"中的"0x"只是指明这是一个十六进制字符串,实际数字只是"ff"(int("ff", 16) ==> 255).

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

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