Printing subscript in python

后端 未结 5 568
逝去的感伤
逝去的感伤 2020-12-03 01:53

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)

5条回答
  •  鱼传尺愫
    2020-12-03 02:38

    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.

提交回复
热议问题