Printing subscript in python

后端 未结 5 547
逝去的感伤
逝去的感伤 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:29

    The output performed on the console is simple text. If the terminal supports unicode (most do nowadays) you can use unicode's subscripts. (e.g H₂) Namely the subscripts are in the ranges:

    • 0x208N for numbers, +, -, =, (, ) (N goes from 0 to F)
    • 0x209N for letters

    For example:

    In [6]: print(u'H\u2082O\u2082')
    H₂O₂
    

    For more complex output you must use a markup language (e.g. HTML) or a typesetting language (e.g. LaTeX).

    0 讨论(0)
  • 2020-12-03 02:33

    Using code like this works too:

    print('\N{GREEK SMALL LETTER PI}r\N{SUPERSCRIPT TWO}')
    print('\N{GREEK CAPITAL LETTER THETA}r\N{SUBSCRIPT TWO}')
    

    The output being:

    πr²
    Θ₂
    

    Note that this works on Python versions 3.3 and higher only. Unicode formatting.

    0 讨论(0)
  • 2020-12-03 02:37

    By using this code you can use alphabets on the superscript and subscript In This code format() is Function and in Format function ('\unicode')

    By using this table (Unicode subscripts and superscripts on Wikipedia) you can give suitable unicode to the suitable one

    you can use superscript and sub script

    "10{}".format('\u00B2')  # superscript 2
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 02:43

    If you want to use it on the axes of a plot you can do:

    import matplotlib.pyplot as plt
    plt.plot([1])
    plt.ylabel(r'$H_{2}$')
    plt.show()
    

    which gives

    0 讨论(0)
提交回复
热议问题