Python Hexadecimal

前端 未结 3 1088
礼貌的吻别
礼貌的吻别 2020-11-29 00:50

How to convert decimal to hex in the following format (at least two digits, zero-padded, without an 0x prefix)?

Input: 255 Output:ff

相关标签:
3条回答
  • 2020-11-29 01:12

    Another solution is:

    >>> "".join(list(hex(255))[2:])
    'ff'
    

    Probably an archaic answer, but functional.

    0 讨论(0)
  • 2020-11-29 01:16

    Use the format() function with a '02x' format.

    >>> format(255, '02x')
    'ff'
    >>> format(2, '02x')
    '02'
    

    The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.

    The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

    >>> format(255, '02X')
    'FF'
    >>> format(255, '#04x')
    '0xff'
    >>> format(255, '#04X')
    '0XFF'
    
    0 讨论(0)
  • 2020-11-29 01:18

    I think this is what you want:

    >>> def twoDigitHex( number ):
    ...     return '%02x' % number
    ... 
    >>> twoDigitHex( 2 )
    '02'
    >>> twoDigitHex( 255 )
    'ff'
    
    0 讨论(0)
提交回复
热议问题