hex()函数的用法及实例,返回十六进制str值

hex()函数描述

hex单词作为名词有十六进制的意思,python的内置函数之一hex()函数的主要功能也是如此,可以将十进制的整型值int转换为十六进制的字符串值。python3中的十六进制值是以“0x”为前缀的字符串。


hex()函数的参数语法结构

下方的这个hex()函数的语法结构来源python3的部分源码:

def hex(__i: Union[int, _SupportsIndex]) -> str

hex()参数

int;python的整型数值;


hex()返回值

以“0x”为前缀的十六进制字符串;


hex()函数实例代码

>>> hex(1)
'0x1'
>>> hex()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hex() takes exactly one argument (0 given)
>>> hex('2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> type(hex(3)) #返回值为字符串类型
<class 'str'>
>>> hex(1.5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

代码解析

如上代码,当直接调用hex()函数且不传递参数的情况下,python抛出TypeError异常,并提示hex()明确需要一个参数;当传递给hex()的参数为字符串时,python又抛出TypeError,并提示字符串对象不能被hex函数像整形数值一样解析编译;当传递给hex()函数的参数为float浮点型数据时,python抛出了同样的TypeError,也给出了类似的提示。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.