Converting numbers to unicode charaters

Laurent Pointal laurent.pointal at limsi.fr
Mon Sep 24 10:21:52 EDT 2007


byte8bits at gmail.com a écrit :
> Here's how I'm doing this right now, It's a bit slow. I've just got
> the code working. I was wondering if there is a more efficient way of
> doing this... simple example from interactive Python:
> 
>>>> word = ''
>>>> hexs = ['42', '72', '61', '64']
>>>> for h in hexs:
> ...   char = unichr(int(h, 16))
> ...   word += char
> ...   print char
> ...
> B
> r
> a
> d
>>>> print word
> Brad
> 
> 
> Each hex_number is two digits. unichr converts that to a character
> that I append to previous ints that have been converted to chars. In
> this way, I convert a string of hex numbers to ints to letters, to
> words.
> 
> Perhaps I'm doing it wrong... any tips?

You have to go by int conversion to get codes, and by unichr to get 
corresponding unicode chars, so this seem the solution.

You may eventually use a more condensed expression and avoid n 
concatenation of n chars using join, like this:

 >>> u''.join(unichr(int(x,16)) for x in ['42','72','61','64'])
u'Brad'




More information about the Python-list mailing list