Printing subscript and superscript in Python

Subscript and superscript are important when you are dealing with different types of formulas. They are useful in math, chemistry, etc.

In Python, there is a method called maketrans. It creates a one to one mapping table with characters and their replacements.

This method will replace 1 to A, 2 to B, and 3 to C. Let’s take a look.

In this case, numbers 1 and 2 are going to be replaced, but 4 doesn’t have a replacement, so it will stay 4.

Printing subscript

Similarly, you can convert numbers to subscript. Let’s use this formula for ethanol:

This code will replace all numbers to subscript, as it should be in the chemical formula.

Printing superscript

You can also convert a number to superscript. In this case, we are going to use a formula to calculate the area of a circle.

In our example, the formula is written this way:

We are going to convert 2 to superscript, and PI to π. We can’t convert PI with maketrans because the first two maketrans arguments should be the same length. In this case, let’s use the replace function.

The result is:

Unicode subscripts and superscripts

Another way to achieve the same result is to use the Unicode subscripts and superscripts.

For subscripts

The letter “x” represents a subscript number.

For superscripts

The letter “x” represents a superscript number.

This is the full table of Unicode characters:

 0123456789ABCDEF
U+00Bx             
U+207xx⁰xⁱ  x⁴x⁵x⁶x⁷x⁸x⁹x⁺x⁻x⁼x⁽x⁾xⁿ
U+208xx₀x₁x₂x₃x₄x₅x₆x₇x₈x₉x₊x₋x₌x₍x₎ 
U+209xxₐxₑxₒxₓxₔxₕxₖxₗxₘxₙxₚxₛxₜ   
Unicode characters

Let’s implement it into Python.

The result is the same as before:

Now, let’s create the second formula:

U+03C0 is a Unicode character for the greek letter PI and U+00B2 for square root. As you can see from the table, the power of 2 and 3 have different notation than numbers from 4 to 9.

The result: