Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing greek letters using sympy in text

Lets say I want to print something like

"I am pi"

where pi should really be the greek letter pi. With sympy I can do

import sympy
from sympy.abc import pi
sympy.pprint(pi)

which gives the greek letter pi, but I have problems putting this into a text. For example

sympy.pprint("I am"+pi)

obviously doesn't work. I can convert the text to a sympy symbol sympy.Symbol('I am'), but then I will get

I am+pi

like image 855
Jonathan Lindgren Avatar asked Oct 21 '14 09:10

Jonathan Lindgren


3 Answers

You want pretty(), which is the same as pprint, but it returns a string instead of printing it.

In [1]: pretty(pi)
Out[1]: 'π'

In [2]: "I am %s" % pretty(pi)
Out[2]: 'I am π'

If all you care about is getting the Unicode character, you can use the Python standard library:

import unicodedata
unicodedata.lookup("GREEK SMALL LETTER %s" % letter.upper()) # for lowercase letters
unicodedata.lookup("GREEK CAPITAL LETTER %s" % letter.upper()) # for uppercase letters
like image 138
asmeurer Avatar answered Nov 14 '22 23:11

asmeurer


You can use unicodedata.lookup to get the Unicode character. In your case you would do like this:

import unicodedata
print("I am " + unicodedata.lookup("GREEK SMALL LETTER PI"))

This gives the following result:

I am π

If you want the capital letter instead, you should do unicode.lookup("GREEK CAPITAL LETTER PI")). You can replace PI with the name of any Greek letter.

like image 39
Donald Duck Avatar answered Nov 14 '22 22:11

Donald Duck


latex and str will both return a string

>>> latex(pi)
'\\pi'
>>> str(pi)
'pi'
like image 36
smichr Avatar answered Nov 14 '22 23:11

smichr