Printing greek letters using sympy in text

非 Y 不嫁゛ 提交于 2019-12-07 06:12:01

问题


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


回答1:


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



回答2:


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.




回答3:


latex and str will both return a string

>>> latex(pi)
'\\pi'
>>> str(pi)
'pi'


来源:https://stackoverflow.com/questions/26483891/printing-greek-letters-using-sympy-in-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!