Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ° character in a string in python?

Tags:

python

string

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

like image 494
Richard Avatar asked Jul 09 '10 17:07

Richard


2 Answers

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

degree_sign = u'\N{DEGREE SIGN}'

Escape Sequence: \N{name}

Meaning: Character named name in the Unicode database

Reference: https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals

Note:

  • "N" must be uppercase 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, i.e. 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]
°-∅
like image 185
tzot Avatar answered Oct 24 '22 01:10

tzot


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

like image 45
John La Rooy Avatar answered Oct 23 '22 23:10

John La Rooy