我正在尝试根据格式将整数转换为十六进制数

I am trying to convert an integer to a hexadecimal number according to the format

通过代码 for i in range(2000,50000) 我想输出从 2000 到 50000 的数字,格式如下:

当我 = 2000 输出:07 D0 当我 = 50000 输出:C3 50

我该怎么做?

你可以这样试试:

def format_hex(number):
    # convert to hex string
    hex_str = hex(number)

    # upper case
    hex_str_upper = hex_str.upper()

    # format 
    hex_value = hex_str_upper[2:]
    if len(hex_value)==3:
        hex_value = '0' + hex_value
    hex_value_output = hex_value[:2] + ' ' + hex_value[2:]

    return hex_value_output

尝试:

def format_hex(i: int) -> str:
    h = hex(i)[2:]
    h = h.zfill(len(h) + len(h) % 2).upper()
    return ' '.join(h[i:i+2] for i in range(0, len(h), 2))

用法:

>>> print(format_hex(2000))
07 D0

>>> print(format_hex(50000))
C3 50