How to Print Superscript in Python?

Problem Formulation

  • Given two strings x and y.
  • Create a new string xy and print it to the shell.

Consider the following examples:

INPUT
x = 'hi'
y = 'finxter'

OUTPUT: hifinxter



INPUT
x = '2'
y = '4'

OUTPUT: 24



INPUT
x = 'abc'
y = '[1, 2, 3]'

OUTPUT: abc[1, 2, 3]

Solution for Jupyter Notebooks

A simple approach is given here:

from IPython.display import display, Math
display(Math('hello^{finxter}'))

A general approach is given here—simply replace x and y with your own variables:

from IPython.display import display, Math
x = 'hello'
y = 'finxter'
display(Math(x + '^{' + y + '}'))

You can try it yourself here:

For Python, it doesn’t work in a general way. The reason is that Unicode doesn’t provide a way to superscript general code. An idea for further investigation would be to use a Latex library that allows you to write and display Latex code within Python.