Add length parameter to hex

Hey everyone!

During my wrok I need to convert int to hex and send it to a server.
The problem is that data I send must be paired. To achieve this I write code like this:

value_to_send = hex(value)[2:]
if len(value_to_send) % 2:
    value_to_send = '0' + value_to_send

My suggestion is to add optional parameter in hex() to automatically pad output with 0

Signature will be changed to

def hex(value, length: int | None = None) -> str: pass

You would use it like so:

>>> hex(13)
# 0xd

>>> hex(13, 2)
# 0x0d

>>> hex(13, 4)
# 0x000d

# We also sould disallow negative numbers as parameters
>>> hex(13, -1)
# 0xd

You can already use f-strings for this (unless I misunderstand what you’re after)

print(f"{0xabc:04x}")
# prints: 0abc

Note that you don’t have to convert the number to hex first for this formatting to work

print(f"{16:03X}")
# prints: 010

See the f-string documentation and the corresponding formatting mini-language guide for more info.

Since this is already available in f-strings, which, IMO, are the most ergonomic way of formatting things like this, I don’t think we need to change the hex builtin.

3 Likes

Thank you! That is exactly what I wanted

1 Like

You can also use the builtin format() function:

>>> format(13, 'x')
'd'
>>> format(13, '#x')
'0xd'
>>> format(13, '04x')
'000d'
>>> format(13, '#06x')
'0x000d'
3 Likes