How to print Superscript and Subscript in Python?
Whenever we are working with formulas there may be a need of writing the given formula in a given format which may require subscripts or superscripts. There are several methods available to print subscripts and superscripts in Python. We will be discussing two of them below –
Using maketrans() and translate() :
We can make two strings one for the normal characters and the other for the subscript/superscript characters. After this, we can use the maketrans() method which returns a mapping that can be used with the translate() method to replace the specified characters. It can be implemented for superscripts as
And for subscripts, we can implement it as
Using Unicode subscripts and superscripts:
The following table gives the subscripts and superscripts of the Unicode characters:
0 1 2 3 4 5 6 7 8 9 A B C D E F U+207x ⁰ ⁱ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹ ⁺ ⁻ ⁼ ⁽ ⁾ ⁿ U+208x ₀ ₁ ₂ ₃ ₄ ₅ ₆ ₇ ₈ ₉ ₊ ₋ ₌ ₍ ₎ U+209x ₐ ₑ ₒ ₓ ₔ ₕ ₖ ₗ ₘ ₙ ₚ ₛ ₜ
With the help of the Unicode character, we can implement this in our codes as –
H₂SO₄ x² + y² = 2
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course