在Python中,hex()是一个内置函数,用于将整数转换为十六进制字符串。其语法如下:
hex(x)
其中,x是一个整数(可以是正整数或负整数),返回值是一个表示x的十六进制字符串;如果x不是int对象,则必须为x定义__index__()方法;
hex() 函数示例
print(hex(255)) # 0xff
print(hex(1234)) # 0x4d2
print(hex(-123)) # -0x7b
print(hex(0xff)) # 0xff
class myclass:
def __index__(self):
return 1
a = myclass()
print(hex(a)) # 0x1
class myclass2:
pass
b = myclass2()
#print(hex(b)) # TypeError
#print(hex(3.14)) # TypeError
hex()函数返回的十六进制字符串包含前缀0x,如果需要去除前缀,可以使用字符串切片来进行处理;例如:
hex(255)[2:]