Format ints into string of hex

前端 未结 10 1742
陌清茗
陌清茗 2020-11-30 08:16

I need to create a string of hex digits from a list of random integers (0-255). Each hex digit should be represented by two characters: 5 - \"05\", 16 - \"10\", etc.

相关标签:
10条回答
  • 2020-11-30 09:09

    Just for completeness, using the modern .format() syntax:

    >>> numbers = [1, 15, 255]
    >>> ''.join('{:02X}'.format(a) for a in numbers)
    '010FFF'
    
    0 讨论(0)
  • 2020-11-30 09:10

    Similar to my other answer, except repeating the format string:

    >>> numbers = [1, 15, 255]
    >>> fmt = '{:02X}' * len(numbers)
    >>> fmt.format(*numbers)
    '010FFF'
    
    0 讨论(0)
  • 2020-11-30 09:11

    The most recent and in my opinion preferred approach is the f-string:

    ''.join(f'{i:02x}' for i in [1, 15, 255])
    

    Format options

    The old format style was the %-syntax:

    ['%02x'%i for i in [1, 15, 255]]
    

    The more modern approach is the .format method:

     ['{:02x}'.format(i) for i in [1, 15, 255]]
    

    More recently, from python 3.6 upwards we were treated to the f-string syntax:

    [f'{i:02x}' for i in [1, 15, 255]]
    

    Format syntax

    Note that the f'{i:02x}' works as follows.

    • The first part before : is the input or variable to format.
    • The x indicates that the string should be hex. f'{100:02x}' is '64' and f'{100:02d}' is '1001'.
    • The 02 indicates that the string should be left-filled with 0's to length 2. f'{100:02x}' is '64' and f'{100:30x}' is ' 64'.
    0 讨论(0)
  • 2020-11-30 09:12
    a = [0,1,2,3,127,200,255]
    print str.join("", ("%02x" % i for i in a))
    

    prints

    000102037fc8ff
    

    (Also note that your code will fail for integers in the range from 10 to 15.)

    0 讨论(0)
提交回复
热议问题