简体   繁体   中英

Formatting hex to be printed with 2 digits?

The built-in function hex() in python returns me a number in the form 0xf or 0x0 but i want them as 0x00. I found this on the python docs but dont really know how to interpret it.

Thanks

You can use string formatting for this purpose:

>>> "0x{:02x}".format(13)
'0x0d'

More detailed examples here:

How can I format an integer to a two digit hex?

In python3, use this f string format:

f"0x{variable:02x}"

For maximum python2/3 compatibility, use .format() :

"0x{:02x}".format(variable)

Here is how:

print('0x'+hex(4)[2:].zfill(2))

Output:

'0x04'


Breaking it down:

  • hex(4) , as you know, will return '0x4' . hex(4)[2:] means to get all the characters in the string after the second one, so it will be '4' .

  • The str.zfill() method will pad a string with the specified number of zeros we pass into the brackets, so hex(4)[2:].zfill(2) will be '04' .

  • Finally, be put the first two characters ( '0x' ) we sliced off in the beginning back to the beginning of the string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM