How to get the ° character in a string in python?

How can I get the character ° (degree) in a string?

+42
python string
Jul 09 '10 at 17:39
source share
5 answers

Put this line at the top of your source

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

If your editor uses a different encoding, replace utf-8

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

+27
Jul 09 '10 at 19:14
source share

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

 degree_sign= u'\N{DEGREE SIGN}' 

Note: there must be capital N in the construction \N to avoid confusion with the newline \ n. The symbol name inside curly braces can be anything.

It's easier to remember the name of a character than its unicode index. It is also more readable, convenient for debugging. The symbol is replaced 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] °-∅ 
+47
Jul 09 '10 at 21:18
source share
 >>> u"\u00b0" u'\xb0' >>> print _ ° 

By the way, all I did was search for a “Unicode degree” on Google. This leads to two results: “Sign of degree U + 00B0” and “Degree of Celsius U + 2103”, which are actually different:

 >>> u"\u2103" u'\u2103' >>> print _ ℃ 
+27
Jul 09 '10 at 17:41
source share

The answers above suggest that UTF8 encoding can be used safely - it is specifically designed for Windows.

The standard Windows console uses the coding CP850 and not utf-8, so if you try to use the source file encoded in utf8, you will get these 2 (incorrect) characters ┬░ instead of degree ° .

Demo (using python 2.7 in windows console):

 deg = u'\xb0` # utf code for degree print deg.encode('utf8') 

effectively outputs ┬░ .

Fix: just force the correct encoding (or better use unicode):

 local_encoding = 'cp850' # adapt for other encodings deg = u'\xb0'.encode(local_encoding) print deg 

or if you use a source file that explicitly defines the encoding:

 # -*- coding: utf-8 -*- local_encoding = 'cp850' # adapt for other encodings print " The current temperature in the country/city you've entered is " + temp_in_county_or_city + "°C.".decode('utf8').encode(local_encoding) 
+6
Jun 07 '16 at 11:46 on
source share

just use \xb0 (in a string); python will automatically convert it

+4
Dec 05 '15 at 4:39 on
source share



All Articles