Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char list from 0 to f

I write a python script, which needs a list of all hexadecimal characters.

Is it a good idea to do list(string.printable[:16]) to get ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'] ?

like image 600
Nachtgold Avatar asked Jan 29 '23 21:01

Nachtgold


2 Answers

The simplest way would be a list comprehension of all numbers from 0 to 15 formatted as hex:

["{:x}".format(x) for x in range(0,16)]

User GarbageCollector suggested a nice alternative in comments, which must be adapted to remove the redundant, uppercased chars:

>>> import string
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.hexdigits[:16]
'0123456789abcdef'

to get a list:

>>> list(string.hexdigits[:16])

the fact that the order of the characters remains the same in string.hexdigits in future python version is however unknown. Still nice to know that string has some many useful characters groups.

like image 181
Jean-François Fabre Avatar answered Feb 12 '23 11:02

Jean-François Fabre


How about doing list('0123456789abcdef') to make it explicit?

If you don't want to spell it out, [f'{i:x}' for i in range(16)] should also work.

like image 26
L3viathan Avatar answered Feb 12 '23 11:02

L3viathan