[Tutor] Creating a unicode string from bytes and % opperator
mail at timgolden.me.uk
Mon Jul 28 11:22:58 CEST 2008
Wesley Brooks wrote:
> I'm trying to create a unicode character from two bytes. Unfortunatly
> I'm getting a "UnicodeDecodeError". Can some one please suggest an
> alternative way of doing what's bellow? In the example bellow the two
> bytes have been converted into a string hex value, but they could just
> as easily be an integer or binary value if either is easier to deal
> Python 2.4.3 - Enthought Edition 1.0.0 (#69, Aug 2 2006, 12:09:59) [MSC v.1310
> 32 bit (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> a = u"\u%s%s" %('0d', 'fe')
> UnicodeDecodeError: 'unicodeescape' codec can't decode bytes in position 0-2: tr
> uncated \uXXXX escape
Nice try :)
Unfortunately, if you think about what's happening here, the
"string interpreter" bit of Python is getting to that
unicode-escape before the "%-processing" bit of Python.
So Python's trying --and failing-- to interpret \u%s%s as some sort of
bizarre unicode escape.
Can you not just use the unichr function?
More information about the Tutor