Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 为什么int(";0xff";,16)计算而int(";hello";,16)不计算?_Python 3.x_String_Integer_Int - Fatal编程技术网

Python 3.x 为什么int(";0xff";,16)计算而int(";hello";,16)不计算?

Python 3.x 为什么int(";0xff";,16)计算而int(";hello";,16)不计算?,python-3.x,string,integer,int,Python 3.x,String,Integer,Int,如果这是个愚蠢的问题,请原谅我。我目前正处于通过Skillsoft课程学习Python的初级阶段。讲师使用的一个例子是:int(“0xff”,16),它计算并打印了255 我只是感到困惑,因为虽然我知道0xff是“整数值为255的hexcidecimal数FF”(谢谢,谷歌),但我不明白“0xff”怎么会因为引号而不被视为字符串。当我尝试int(“hello”,16)时,我遇到了: Traceback (most recent call last): File "<pyshell#25

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

我只是感到困惑,因为虽然我知道0xff是“整数值为255的hexcidecimal数FF”(谢谢,谷歌),但我不明白“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'
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
int(“你好”,16)
ValueError:基数为16的int()的文本无效:“hello”
当“0xff”和“hello”都是字符串时,
int(“0xff”,16)
如何计算而不是
int(“hello”,16)
呢?

因为
“0xff”
是一个表示十六进制数(base
16
)的字符串,而十六进制数字的数字范围是从
0
9
和从
a
f
“hello”
“h”
“l”
“o”
,它们都不是有效的十六进制数字

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

为了了解为什么允许字符串,请考虑<代码> 17 < /C> >基数系统(<代码> 09和<代码> AG/<代码>),在系统中使用“<代码> > GG”< /C> >“代码> int(“GG”,17)< /代码> < /P>。 可以将

int
“hello”
一起使用,但只能使用大于或等于
25
(因为
10+ord(max(“hello”)-97+1==25
),
int(“hello”,25)==>6873049