Hướng dẫn python format hex string

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.

Example:

Input: [0,1,2,3,127,200,255], 
Output: 000102037fc8ff

I've managed to come up with:

#!/usr/bin/env python

def format_me[nums]:
    result = ""
    for i in nums:
        if i >> numbers = [1, 15, 255]
>>> ''.join['{:02X}'.format[a] for a in numbers]
'010FFF'

answered Nov 15, 2013 at 8:37

gakgak

31.4k26 gold badges117 silver badges153 bronze badges

''.join['%02x'%i for i in input]

answered Apr 14, 2011 at 10:18

vartecvartec

127k36 gold badges213 silver badges242 bronze badges

2

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', f'{100:02d}' [decimal] is '100' and f'{100:02b}' [binary] is '1100100'.
  • The 02 indicates that the string should be left-filled with 0's to minimum length 2. f'{100:02x}' is '64' and f'{100:30x}' is ' 64'.

See pyformat for more formatting options.

answered Jul 25, 2019 at 8:47

RoelantRoelant

3,9371 gold badge27 silver badges56 bronze badges

3

Python 2:

>>> str[bytearray[[0,1,2,3,127,200,255]]].encode['hex']
'000102037fc8ff'

Python 3:

>>> bytearray[[0,1,2,3,127,200,255]].hex[]
'000102037fc8ff'

answered Apr 14, 2011 at 10:31

John La RooyJohn La Rooy

286k51 gold badges358 silver badges498 bronze badges

2

Yet another option is binascii.hexlify:

a = [0,1,2,3,127,200,255]
print binascii.hexlify[bytes[bytearray[a]]]

prints

000102037fc8ff

This is also the fastest version for large strings on my machine.

In Python 2.7 or above, you could improve this even more by using

binascii.hexlify[memoryview[bytearray[a]]]

saving the copy created by the bytes call.

answered Apr 14, 2011 at 10:54

Sven MarnachSven Marnach

544k114 gold badges914 silver badges816 bronze badges

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

>>> numbers = [1, 15, 255]
>>> fmt = '{:02X}' * len[numbers]
>>> fmt.format[*numbers]
'010FFF'

answered Apr 19, 2014 at 20:31

gakgak

31.4k26 gold badges117 silver badges153 bronze badges

1

Starting with Python 3.6, you can use f-strings:

>>> number = 1234
>>> f"{number:04x}"
'04d2'

answered Apr 25, 2021 at 13:34

roskakoriroskakori

2,8691 gold badge27 silver badges27 bronze badges

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.]

answered Apr 14, 2011 at 10:17

Sven MarnachSven Marnach

544k114 gold badges914 silver badges816 bronze badges

From Python documentation. Using the built in format[] function you can specify hexadecimal base using an 'x' or 'X' Example:

x= 255 print['the number is {:x}'.format[x]]

Output:

the number is ff

Here are the base options

Type
'b' Binary format. Outputs the number in base 2. 'c' Character. Converts the integer to the corresponding unicode character before printing. 'd' Decimal Integer. Outputs the number in base 10. 'o' Octal format. Outputs the number in base 8. 'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9. 'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9. 'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters. None The same as 'd'.

Dharman

28k21 gold badges75 silver badges127 bronze badges

answered Oct 3, 2020 at 19:49

1

With python 2.X, you can do the following:

numbers = [0, 1, 2, 3, 127, 200, 255]
print "".join[chr[i].encode['hex'] for i in numbers]

print

'000102037fc8ff'

answered Jul 25, 2018 at 1:28

selfbootselfboot

1,43018 silver badges23 bronze badges

Example with some beautifying, similar to the sep option available in python 3.8

def prettyhex[nums, sep='']:
    return sep.join[f'{a:02x}' for a in nums]

numbers = [0, 1, 2, 3, 127, 200, 255]
print[prettyhex[numbers,'-']]

output

00-01-02-03-7f-c8-ff

answered Jun 15, 2020 at 8:41

MarcoMarco

4906 silver badges9 bronze badges

Using python string format[] this can be done.

Code:

n = [0,1,2,3,127,200,255]
s = "".join[[format[i,"02X"] for i in n]]
print[s]

Output:

000102037FC8FF

answered Jan 16 at 12:09

Chủ Đề