Printing subscript in python

samrobbins picture samrobbins · Jun 24, 2014 · Viewed 85.6k times · Source

In Python 3.3, is there any way to make a part of text in a string subscript when printed?

e.g. H₂ (H and then a subscript 2)

Answer

Zero Piraeus picture Zero Piraeus · Jun 24, 2014

If all you care about are digits, you can use the str.maketrans() and str.translate() methods:

>>> SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
>>> SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
>>> "H2SO4".translate(SUB)
'H₂SO₄'

Note that this won't work in Python 2 - see Python 2 maketrans() function doesn't work with Unicode for an explanation of why that's the case, and how to work around it.