I wanted to know if there is any way I can print x^2 in string format like we do in mathematics like x2. where 2 is in exponential form in top right corner of x.
Asked
Active
Viewed 1,276 times
1
-
3You can take a look at this related question: https://stackoverflow.com/questions/4028267/print-latex-formula-with-python – Tom Leung Feb 09 '20 at 07:08
-
Do you need something general (any n^m) or just for two? If just the latter, you could use https://unicode-table.com/en/00B2/ – petre Feb 09 '20 at 07:23
-
Python strings can contain Unicode characters, so `print('x²')` works fine. – kaya3 Feb 09 '20 at 07:46
1 Answers
2
How about:
def stringify_exponent(n, m):
superscripted = "".join(_DIGITS[int(d)] for d in str(m))
return f"{n}{superscripted}"
_DIGITS = [
"\N{superscript zero}",
"\N{superscript one}",
"\N{superscript two}",
"\N{superscript three}",
"\N{superscript four}",
"\N{superscript five}",
"\N{superscript six}",
"\N{superscript seven}",
"\N{superscript eight}",
"\N{superscript nine}"
]
if __name__ == "__main__":
print(stringify_exponent(10, 2))
print(stringify_exponent(2, 1024))
Printing:
10²
2¹⁰²⁴

petre
- 1,485
- 14
- 24