Dekorowanie funkcji Hex do padów zer

Napisałem taką prostą funkcję:

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)

Przykłady:

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

Chociaż jest to dla mnie wystarczająco jasne i pasuje do mojego przypadku użycia (proste narzędzie testowe dla prostej drukarki), nie mogę przestać myśleć, że jest dużo miejsca na ulepszenia i może to zostać zmiażdżone do czegoś bardzo zwięzłego.

Jakie są inne podejścia do tego problemu?

Author: Tim Pietzcker, 2012-09-28

3 answers

Użyj nowego .format() metoda string:

>>> "{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

Jeśli chcesz, aby cyfry szesnastkowe były duże, ale przedrostek z małą literą "x", potrzebujesz lekkiego obejścia:

>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'

Począwszy od Pythona 3.6, możesz również to zrobić:

>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'
 113
Author: Tim Pietzcker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 15:48:17

A może tak:

print '0x%04x' % 42
 19
Author: georg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-28 10:40:55

Użyj *, aby przekazać szerokość i {[2] } dla wielkich liter

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

Zgodnie z sugestią georg i Ashwini Chaudhary

 3
Author: GabrielOshiro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:17:49