[Tutor] unicode characters from integers?

Chris or Leslie Smith smiles at worksmail.net
Wed Nov 9 18:52:08 CET 2005


I know that chr() can be used to convert an integer into an ASCII character, but I am having a hard time trying to generate unicode characters from numbers.  e.g. say I want to generate u'\u0950' from the integer 950, does anyone know if/how this can be done? Here are some failures:

###
>>> unicode(950)
u'950'
>>> 
>>> u'\u%04i' % 950
Traceback (UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-2: truncated \uXXXX escape
>>> 
>>> unicode('\u%04i' % 950)
u'\\u0950'
>>> 
>>> unicode('\\u%04i' % 950) #double \\
u'\\u0950'
###

Here is a successful method, but is there a better way? (Please don't clobber me if there is a very simple way to do this ;-).)

import StringIO
def uni(x): #convert hexadecimal x into string representation and return as unicode escape char
    s=StringIO.StringIO()
    s.write('0000')
    x=hex(x).split('x')[1]
    s.seek(4-len(x))
    s.write(x)
    s.seek(0)
    return eval(unicode("u'\u%s'" % s.read()))

###
>>> uni(0x095a)
u'\u095a'
>>> type(_) #check if it's right
<type 'unicode'>
>>> 
###

/c


More information about the Tutor mailing list