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.
1 |
replace = str.maketrans("123", "ABC") |
This method will replace 1 to A, 2 to B, and 3 to C. Let’s take a look.
1 2 |
numbers_to_letters = str.maketrans("123", "ABC") print("Question 1, point 2 and 4".translate(numbers_to_letters)) |
In this case, numbers 1 and 2 are going to be replaced, but 4 doesn’t have a replacement, so it will stay 4.
Question A, point B and 4
Printing subscript
Similarly, you can convert numbers to subscripts. Let’s use this formula for ethanol:
1 2 |
subscript = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉") print("C2H5OH".translate(subscript)) |
This code will replace all numbers with subscripts, as it should be in the chemical formula.
C₂H₅OH
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.
πr²
In our example, the formula is written this way:
PIr2
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.
1 2 |
superscript = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹") print("PIr2".translate(superscript).replace('PI', 'π')) |
The result is:
πr²
Unicode subscripts and superscripts
Another way to achieve the same result is to use Unicode subscripts and superscripts.
For subscripts
U+207x
The letter “x” represents a subscript number.
For superscripts
U+208x
The letter “x” represents a superscript number.
This is the full table of Unicode characters:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F | |
U+00Bx | x² | x³ | x¹ | |||||||||||||
U+207x | x⁰ | xⁱ | x⁴ | x⁵ | x⁶ | x⁷ | x⁸ | x⁹ | x⁺ | x⁻ | x⁼ | x⁽ | x⁾ | xⁿ | ||
U+208x | x₀ | x₁ | x₂ | x₃ | x₄ | x₅ | x₆ | x₇ | x₈ | x₉ | x₊ | x₋ | x₌ | x₍ | x₎ | |
U+209x | xₐ | xₑ | xₒ | xₓ | xₔ | xₕ | xₖ | xₗ | xₘ | xₙ | xₚ | xₛ | xₜ |
Let’s implement it into Python.
1 |
print(u'C\u2082H\u2085OH') |
The result is the same as before:
C₂H₅OH
Now, let’s create the second formula:
1 |
print(u'\u03C0r\u00B2') |
U+03C0 is a Unicode character for the greek letter PI and U+00B2 for the 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:
πr²