Format ints into string of hex

前端 未结 10 1759
陌清茗
陌清茗 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: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'.

提交回复
热议问题