Python convert integer to hexadecimal string

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 hexadecimal string form, such as 125 to'0x7D'This, the following two methods to achieve this goal,

1. Using hex()

data = 125
  • 1
  • 2

The print is as follows.
insert image description here
If the integer data is 2, it is printed as
insert image description here
You can see that hex() can indeed convert an integer to a string in hexadecimal form, but it is a bit of a fly in the ointment. For example, A~F characters can only be lowercase, and the number is 16 The following will occupy only one position, and sometimes multiple data will be printed. I hope that they will occupy 2 positions in a neat and uniform manner, which cannot meet the demand. In this case, the format() method can be used.

2. Using format()

format() is a very powerful method. Its function is similar to printf in C language. It is also very simple and convenient to use.

data1 = 125
data2 = 2
str1 = '0x{:02X}'.format(data1)
str2 = '0x{:02X}'.format(data2)
print(str1, str2)
  • 1
  • 2
  • 3
  • 4
  • 5

The output is as follows,
insert image description here
:02X indicates that the output is in hexadecimal format, and there are 2 placeholders.

The format() method can print various formats according to the user's needs, and can replace the previous % printing method. For specific operations, you can view the relevant information.

Related: Python convert integer to hexadecimal string