Displaying Unicode Chars

gregpinero at gmail.com gregpinero at gmail.com
Sun Feb 10 23:37:38 EST 2008


On Feb 10, 4:30 pm, "Martin v. Löwis" <mar... at v.loewis.de> wrote:
> > I want to make a little Python utility where a user can enter the
> > unicode numerical code and get the actual symbol back in utf-8.
>
> > For example, a user could enter something like u221E
>
> I'm puzzled why the user would enter "u221E" - why not just "221E"?
>
> > And get back ∞
>
> > Now, this does seem to work:
>
> >>>> print u"\u221E"
> > ∞
> > However how can I change it so it works with a string variable?
>
> The problem is not with variables - print can output variables
> just fine:
>
> text = u"\u221E"
> print text
>
> (where text is a variable holding a Unicode string)
>
> Your problem is with data conversion: how to convert a string
> holding a hexadecimal integer number into a Unicode
> character whose ordinal is that number?
Thanks to both of you.  Those approaches make sense.  Here's the final
result if you're curious: http://utilitymill.com/utility/Display_Unicode_Char_From_Hex

-Greg


> To do so, you need two steps (assuming you start from "221E")
> 0. char = "221E"
> 1. convert that into an integer: char = int(char, 16)
> 2. convert that into a Unicode character: char = unichr(char)
> 3. print it: print char
>
> If you insist on the user entering "u221E" instead, you have
> to convert that first into a string without the leading u:
>
> 0.5 char = char[1:]
>
> HTH,
> Martin




More information about the Python-list mailing list