How to get a unicode degrees symbol?

Fredrik Lundh fredrik at pythonware.com
Tue Jun 5 12:59:11 EDT 2001


Russell E. Owen wrote:
> I'm obvious missing some important bit of documentation, but I looked
> through the manuals and can't seem to figure out how to get unicode
> character constants into python strongs.

not sure how you managed to miss this one:

    http://www.python.org/doc/current/ref/strings.html

but here's a summary: either use a 2, 4 or 8-digit hexadecimal
character code:

    u"\xb0", u"\u00b0", u"\U000000b0"

or a named unicode character:

    u"\N{DEGREE SIGN}"

> For instance I'd like to create a string that contains a degree symbol
> (that would show up correctly on all platforms).  Right now I'm
> generating a character constant whose contents are set differently
> depend on the platform. It works but is rather lame.

if you need different *content* for different platforms, unicode won't
help you.  it's only a character encoding, after all...

if you want the same content, but want to print it in different ways
depending on the platform's display encoding, you can use the encode
method on the way out.  examples:

    u = u"\N{DEGREE SIGN}"
    print u.encode("iso-8859-1") # unix (us/western europe)
    print u.encode("cp1252") # windows
    print u.encode("macroman") # macintosh
    print u.encode("cp850") # dos window

if the target encoding doesn't have a degree sign, encode will raise
an exception.  if you don't want that, pass "replace" or "ignore" as
the second argument.

</F>





More information about the Python-list mailing list