How to print hexadecimal in Python?

In Python, you can use the hex() function to convert an integer to a hexadecimal string.

Here is an example of outputting hexadecimal using the hex() function:

num = 255
hex_value = hex(num)
print(hex_value)  # 输出:0xff

Please note that the hex() function returns a string representing the hexadecimal representation of an integer. If you need to remove the prefix 0x, you can use string slicing or the format() function.

num = 255
hex_value = hex(num)[2:]  # 切片操作去掉前缀0x
print(hex_value)  # 输出:ff

hex_value = format(num, 'x')  # 使用format()函数
print(hex_value)  # 输出:ff

If you want to convert a string to its corresponding hexadecimal representation, you can use the str.encode() method.

text = "hello"
hex_value = text.encode().hex()
print(hex_value)  # 输出:68656c6c6f

In this example, the str.encode() method converts a string to a byte sequence, while the .hex() method converts a byte sequence to a hexadecimal string.

bannerAds