tags:

views:

165

answers:

3

How can I get a ° character into a string?

+11  A: 
>>> u"\u00b0"
u'\xb0'
>>> print _
°

BTW, all I did was search "unicode degree" on Google. This brings up two results: "Degree sign U+00B0" and "Degree Celsius U+2103", which are actually different:

>>> u"\u2103"
u'\u2103'
>>> print _
℃
adamk
Or just `a = '\u00b0'` in Python 3.
JAB
@JAB: or just `a='°'`.
SilentGhost
@SilentGhost: Well yeah, but I didn't remember the numpad code for ° and didn't feel like looking it up at the time.
JAB
+4  A: 

Put this line at the top of your source

# -*- coding: utf-8 -*-

If your editor uses a different encoding, substitute for utf-8

Then you can include utf-8 characters directly in the source

gnibbler
Assuming your editor does UTF-8. If your editor uses a different charset then indicate that instead.
Ignacio Vazquez-Abrams
# -*- coding: cp1252 -*- is what worked for me
Richard
+8  A: 

This is the most coder-friendly version of specifying a unicode character:

degree_sign= u'\N{DEGREE SIGN}'

Note: must be a capital N in the \N construct to avoid confusion with the '\n' newline character. The character name inside the curly braces can be any case.

It's easier to remember the name of a character than its unicode index. It's also more readable, ergo debugging-friendly. The character substitution happens at compile time: the .py[co] file will contain a constant for u'°':

>>> import dis
>>> c= compile('u"\N{DEGREE SIGN}"', '', 'eval')
>>> dis.dis(c)
  1           0 LOAD_CONST               0 (u'\xb0')
              3 RETURN_VALUE
>>> c.co_consts
(u'\xb0',)
>>> c= compile('u"\N{DEGREE SIGN}-\N{EMPTY SET}"', '', 'eval')
>>> c.co_consts
(u'\xb0-\u2205',)
>>> print c.co_consts[0]
°-∅
ΤΖΩΤΖΙΟΥ