在python中打印下标

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24391892/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:32:09  来源:igfitidea点击:

Printing subscript in python

pythonpython-3.xpython-3.3subscript

提问by samrobbins

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

在 Python 3.3 中,有没有办法在打印时在字符串下标中制作一部分文本?

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

例如H?(H然后一个下标2)

采纳答案by Zero Piraeus

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

如果您只关心数字,则可以使用str.maketrans()str.translate()方法:

>>> SUB = str.maketrans("0123456789", "??????????")
>>> SUP = str.maketrans("0123456789", "?123??????")
>>> "H2SO4".translate(SUB)
'H?SO?'

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

请注意,这在 Python 2 中不起作用 - 请参阅Python 2 maketrans() 函数不适用于Unicode以解释为什么会出现这种情况以及如何解决它。

回答by Bakuriu

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:

在控制台上执行的输出是简单的文本。如果终端支持 unicode(现在大多数都支持),您可以使用unicode's subscripts。(例如 H?)即下标在以下范围内:

  • 0x208N for numbers, +, -, =, (, )(Ngoes from 0to F)
  • 0x209N for letters
  • 0x208N 表示数字, +, -, =, (, )(N0F)
  • 0x209N 代表字母

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).

对于更复杂的输出,您必须使用标记语言(例如 HTML)或排版语言(例如 LaTeX)。

回答by Hemant Bawane

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

通过使用此代码,您可以在上标和下标上使用字母 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

通过使用此表(维基百科上的 Unicode 下标和上标),您可以为合适的人提供合适的 unicode

you can use superscript and sub script

您可以使用上标和下标

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

回答by Shirsho

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:

输出为:

πr2
Θ?

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

请注意,这仅适用于 Python 3.3 及更高版本。Unicode 格式。