Displaying Unicode Chars

"Martin v. Löwis" martin at v.loewis.de
Sun Feb 10 16:30:19 EST 2008


> 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?

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