How to Print Subscript in Python?

Rate this post

Problem Formulation

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

Consider the following examples:

x = 'hi'
y = 'finxter'

OUTPUT: hifinxter

x = '2'
y = '4'


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

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 subscript 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.