Printing subscript in python
Printing subscript in python
If all you care about are digits, you can use the str.maketrans()
and str.translate()
methods:
example_string = A0B1C2D3E4F5G6H7I8J9
SUB = str.maketrans(0123456789, ₀₁₂₃₄₅₆₇₈₉)
SUP = str.maketrans(0123456789, ⁰¹²³⁴⁵⁶⁷⁸⁹)
print(example_string.translate(SUP))
print(example_string.translate(SUB))
Which will output:
A⁰B¹C²D³E⁴F⁵G⁶H⁷I⁸J⁹
A₀B₁C₂D₃E₄F₅G₆H₇I₈J₉
Note that this wont work in Python 2 – see Python 2 maketrans() function doesnt work with Unicode for an explanation of why thats the case, and how to work around it.
The output performed on the console is simple text. If the terminal supports unicode (most do nowadays) you can use unicodes subscripts. (e.g H₂) Namely the subscripts are in the ranges:
- 0x208N for numbers,
+
,-
,=
,(
,)
(N
goes from0
toF
) - 0x209N for letters
For example:
In [6]: print(uHu2082Ou2082)
H₂O₂
For more complex output you must use a markup language (e.g. HTML) or a typesetting language (e.g. LaTeX).
Printing subscript in python
Using code like this works too:
print(N{GREEK SMALL LETTER PI}rN{SUPERSCRIPT TWO})
print(N{GREEK CAPITAL LETTER THETA}rN{SUBSCRIPT TWO})
The output being:
πr²
Θ₂
Note that this works on Python versions 3.3 and higher only. Unicode formatting.