Sunday, November 17, 2024
Google search engine
HomeLanguagesHow to print Superscript and Subscript in Python?

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 

Python3




# function to convert to superscript
def get_super(x):
    normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()"
    super_s = "ᴬᴮᶜᴰᴱᶠᴳᴴᴵᴶᴷᴸᴹᴺᴼᴾQᴿˢᵀᵁⱽᵂˣʸᶻᵃᵇᶜᵈᵉᶠᵍʰᶦʲᵏˡᵐⁿᵒᵖ۹ʳˢᵗᵘᵛʷˣʸᶻ⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾"
    res = x.maketrans(''.join(normal), ''.join(super_s))
    return x.translate(res)
  
# display superscipt
print(get_super('Lazyroar')) #ᴳᵉᵉᵏˢᶠᵒʳᴳᵉᵉᵏˢ


Output:

ᴳᵉᵉᵏˢᶠᵒʳᴳᵉᵉᵏˢ

And for subscripts, we can implement it as

Python3




# function to convert to subscript
def get_sub(x):
    normal = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-=()"
    sub_s = "ₐ₈CDₑբGₕᵢⱼₖₗₘₙₒₚQᵣₛₜᵤᵥwₓᵧZₐ♭꜀ᑯₑբ₉ₕᵢⱼₖₗₘₙₒₚ૧ᵣₛₜᵤᵥwₓᵧ₂₀₁₂₃₄₅₆₇₈₉₊₋₌₍₎"
    res = x.maketrans(''.join(normal), ''.join(sub_s))
    return x.translate(res)
  
# display subscript
print('H{}SO{}'.format(get_sub('2'),get_sub('4'))) #H₂SO₄


Output:

H₂SO₄

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 –

Python3




# subscript
print(u'H\u2082SO\u2084'# H₂SO₄
  
# superscript
print("x\u00b2 + y\u00b2 = 2"# x² + y² = 2


Output:

H₂SO₄
x² + y² = 2

RELATED ARTICLES

Most Popular

Recent Comments