python-3.x - 为什么 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)
解决方案
因为"0xff"
是表示十六进制数(基数16
)的字符串,十六进制数的数字范围从0
to9
和 from a
to 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)
您可以使用int
with "hello"
,但只能使用大于或等于的基数25
(因为10 + ord(max("hello")) - 97 + 1 == 25
),int("hello", 25) ==> 6873049
。
推荐阅读
- html - 角度 7 变化前图像闪烁
- java - ApiException 需要 Throwable,发现 CustomException
- python - 如果日期在当前索引和上一个索引之间,则将值添加到具有“日期时间”索引的数据框的当前行
- c++ - C 字符串作为模板非类型参数适用于 gcc 6.3,但不适用于 Visual Studio 2017(19.16.27027.1 for x64)
- javascript - 使用 JQuery Find 方法在 HTML 表中查找复选框
- odoo - Odoo 继承字段和功能
- linux - 指定 GCC 输出二进制文件的预期 Linux 版本
- dart - 如何从flutter redux中的void方法调用调度动作
- javascript - 角 matMenuTriggerRestoreFocus 不起作用
- reference - Prolog比较变量的方法