We want to convert an integer data into a string. The common way is to use str() directly, but sometimes we want to convert it into a hexadecimal string form, such as 125 to '0x7D'
this. Here are two ways to achieve it. For this purpose,
1. Use hex()
data = 125
print(hex(data))
The printing is as follows,
if the integer data is 2, it
can be seen that hex() can indeed convert the integer to a hexadecimal string, but it is a little flawed, such as A~F characters can only be lowercase, and the number is 16. The following will only occupy one position, sometimes printing multiple data, hoping to occupy 2 positions neatly, which cannot meet the demand. At this time, you can use the format() method.
2. Use format()
format() is a very powerful method, the function is similar to printf in C language, and it is very simple and convenient to use.
data1 = 125
data2 = 2
str1 = '0x{:02X}'.format(data1)
str2 = '0x{:02X}'.format(data2)
print(str1, str2)
The output is as follows,
:02X means the output is in hexadecimal format, with 2 placeholders.
The format() method can print various formats according to user needs, and can replace the previous% printing method. For specific operations, you can view relevant information.