Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

math - How do you print superscript in Python?

I am aware of the xb function in python, but it does not seem to work for me. I am aware that I may need to download a third party module to accomplish this, if so, which one would be best?

I am currently writing a binomial expansion solver, to try and use skills which I am teaching myself. The problem arises when I attempt to display the user input-ed expansion to the use for confirmation. Currently I am having to print the expression like so:

var1 = input("Enter a: ")
var2 = input("Enter b: ")
exponent = input("Enter n: ")

a = int(var1)
b = int(var2)
n = int(exponent)

expression = ('(%(1)dx%(2)d)^%(3)d') %
{'1' : a, '2' : b, '3' : n}

print(expression)

confirmation = input(str("Is this correctt? Y/N "))

This prints (2x4)^5, whereas I'd prefer the index to be printed as superscript. How can this be done?

question from:https://stackoverflow.com/questions/65598361/python-3-how-to-print-a-superscript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You could use sympy module that does necessary formatting for you. It supports many formats such as ascii, unicode, latex, mathml, etc:

from sympy import pretty_print as pp, latex
from sympy.abc import a, b, n

expr = (a*b)**n
pp(expr) # default
pp(expr, use_unicode=True)
print(latex(expr))
print(expr.evalf(subs=dict(a=2,b=4,n=5)))

Output

     n
(a*b) 
     n
(a?b) 
$left(a b
ight)^{n}$
32768.0000000000

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...