Print index in python

In Python 3.3, is there a way to make part of the text in a string index when printing?

eg. H₂ (H then index 2)

+6
source share
4 answers

If you only have numbers, you can use and : str.maketrans() str.maketrans() str.translate()

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

Note that this will not work in Python 2 - see the Python 2 function maketrans () does not work with Unicode to explain why this is so and how to get around this.

+18
source

- . unicode ( ), Unicode. (, H₂). , :

  • 0x208N , +, -, =, (, ) (N 0 F)
  • 0x209N

:

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

(, HTML) (, LaTeX).

+10

, . () , ('\ unicode')

( ), .

You can use superscript and helper script

"10{}".format('\u00B2')  # superscript 2
0
source

Using this code also works:

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

The output is:

πr²
Θ₂

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

0
source

Source: https://habr.com/ru/post/1545876/


All Articles