113

I wrote this simple function:

def padded_hex(i, l):
    given_int = i
    given_len = l

    hex_result = hex(given_int)[2:] # remove '0x' from beginning of str
    num_hex_chars = len(hex_result)
    extra_zeros = '0' * (given_len - num_hex_chars) # may not get used..

    return ('0x' + hex_result if num_hex_chars == given_len else
            '?' * given_len if num_hex_chars > given_len else
            '0x' + extra_zeros + hex_result if num_hex_chars < given_len else
            None)

Examples:

padded_hex(42,4) # result '0x002a'
hex(15) # result '0xf'
padded_hex(15,1) # result '0xf'

Whilst this is clear enough for me and fits my use case (a simple test tool for a simple printer) I can't help thinking there's a lot of room for improvement and this could be squashed down to something very concise.

What other approaches are there to this problem?

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
jon
  • 5,986
  • 5
  • 28
  • 35

9 Answers9

264

Starting with Python 3.6, you can:

>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'

for older python versions use the .format() string method:

>>> "{0:#0{1}x}".format(42,6)
'0x002a'

Explanation:

{   # Format identifier
0:  # first parameter
#   # use "0x" prefix
0   # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x   # hexadecimal number, using lowercase letters for a-f
}   # End of format identifier

If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround:

>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
Neuron
  • 5,141
  • 5
  • 38
  • 59
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • Is it possible to write this as a format string in python 3.6? – Richard Neumann Mar 08 '18 at 09:36
  • Yes, but without any success, since I cannot figure out the correct syntax for it: `value = 42; padding = 6; f"{value:#0{padding}x}"` throws a syntax error: ` File "", line 1 f"{value:#0{padding}x}" ^ SyntaxError: invalid syntax` – Richard Neumann Mar 08 '18 at 15:29
  • This works for me on Python 3.6.4. Try `import sys; print(sys.version)` to make sure you're running the correct interpreter. – Tim Pietzcker Mar 08 '18 at 15:45
  • python really likes to complicate things up – user7082181 Mar 22 '21 at 19:46
  • Can I have a lowercase 'x' with an upper case hex, like `0x002A` with this format solution? – Katu Jul 21 '21 at 08:30
  • 1
    @Katu: You can do `f"{value:#0{padding}X}".replace("X","x")` – Tim Pietzcker Jul 22 '21 at 05:07
  • Sorry... None of what I read here works for negative numbers... Try this instead: val = 42 nbits = 16 "{:0>4s}".format(hex((val + (1 << nbits)) % (1 << nbits))[2:]).upper() – karelv Oct 25 '21 at 22:03
37

How about this:

print '0x%04x' % 42
georg
  • 211,518
  • 52
  • 313
  • 390
35

If you don't need to handle negative numbers, you can do

"{:02x}".format(7)   # '07'
"{:02x}".format(27)  # '1b'

Where

  • : is the start of the formatting specification for the first argument {} to .format()
  • 02 means "pad the input from the left with 0s to length 2"
  • x means "format as hex with lowercase letters"

You can also do this with f-strings:

f"{7:02x}"   # '07'
f"{27:02x}"  # '1b'
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
20

If just for leading zeros, you can try zfill function.

'0x' + hex(42)[2:].zfill(4) #'0x002a'
Xinyi Li
  • 852
  • 8
  • 9
7

Use * to pass width and X for uppercase

print '0x%0*X' % (4,42) # '0x002A'

As suggested by georg and Ashwini Chaudhary

Community
  • 1
  • 1
GabrielOshiro
  • 7,986
  • 4
  • 45
  • 57
5

If you want to hold the preceding hex notation 0x you can also try this method too which is using the python3 f-strings.

    f'0x{10:02x}' # 0x0a
ABHIJITH EA
  • 308
  • 4
  • 13
2

None of the answers are dealing well with negative numbers...
Try this:

val = 42
nbits = 16
'{:04X}'.format(val & ((1 << nbits)-1))

enter image description here

karelv
  • 756
  • 9
  • 20
  • ```'{:0{}X}'.format(val & ((1 << nbits)-1), int((nbits+3)/4))``` will set the width correct. – karelv Oct 25 '21 at 22:26
1

Suppose you want to have leading zeros for hexadecimal number, for example you want 7 digit where your hexadecimal number should be written on, you can do like that :

hexnum = 0xfff
str_hex =  hex(hexnum).rstrip("L").lstrip("0x") or "0"
'0'* (7 - len(str_hexnum)) + str_hexnum

This gives as a result :

'0000fff'
1

This will give you a random HexDec String [000001 - FFFFFF]:

# !/usr/bin/python39
import random

f'{random.randint(1, 16777215):06x}'.upper()
Kimo Saper
  • 11
  • 2