Equivalent to chr(eval(self.myhex)) without using eval?

Bengt Richter bokr at oz.net
Wed Dec 18 19:47:46 EST 2002


On Wed, 18 Dec 2002 22:36:31 -0000, claird at lairds.com (Cameron Laird) wrote:

>In article <mailman.1040243490.26231.python-list at python.org>,
>Tim Peters <tim at zope.com> wrote:
>>[Jeff Kowalczyk]
>>> I have a class instance attribute which is a string representation of a
>>> hex value. I need to get the chr() character back.
>>
>>>>> ashex = '2a'
>>>>> chr(eval('0x' + ashex))
>>'*'
>>>>> chr(int(ashex, 16))
>>'*'
>>>>> import binascii
>>>>> binascii.unhexlify(ashex)
>>'*'
>>>>>
>>
>
>Python:  the language which offers more than one wizardly way
>to do something.

For single character hex values 00 to ff (or FF), you might consider making
your own lookup dict:

 >>> ashex = '2a'
 >>> hex2chr = dict([(fmt%x,chr(x)) for x in range(256) for fmt in ('%02x','%02X')])
 >>> hex2chr[ashex]
 '*'
 >>> hex2chr['2A']
 '*'
 >>> hex2chr['2z']
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
 KeyError: 2z

Or avoid the exception and substitute a default
 >>> hex2chr.get('2z','?')
 '?'

Regards,
Bengt Richter



More information about the Python-list mailing list