简体   繁体   English

如何在 Python 中打印上标?

[英]How do you print superscript in Python?

I am aware of the \xb function in python, but it does not seem to work for me.我知道 python 中的 \xb function,但它似乎对我不起作用。 I am aware that I may need to download a third party module to accomplish this, if so, which one would be best?我知道我可能需要下载第三方模块来完成此操作,如果是这样,哪个最好?

I am currently writing a binomial expansion solver, to try and use skills which I am teaching myself.我目前正在编写一个二项式展开求解器,以尝试使用我正在自学的技能。 The problem arises when I attempt to display the user input-ed expansion to the use for confirmation.当我尝试显示用户输入的扩展以供确认时出现问题。 Currently I am having to print the expression like so:目前我必须像这样打印表达式:

var1 = input("Enter a: ")
var2 = input("Enter b: ")
exponent = input("Enter n: ")

a = int(var1)
b = int(var2)
n = int(exponent)

expression = ('(%(1)dx%(2)d)^%(3)d') %\
{'1' : a, '2' : b, '3' : n}

print(expression)

confirmation = input(str("Is this correctt? Y/N "))

This prints (2x4)^5, whereas I'd prefer the index to be printed as superscript.这将打印 (2x4)^5,而我更希望将索引打印为上标。 How can this be done?如何才能做到这一点?

You need to use a 'format' type thing.您需要使用“格式”类型的东西。 Use {}\²".format(area))" and the {} becomes a ²`.使用{}\²".format(area))" and the {} becomes a ²`。 Here is an example:下面是一个例子:

print("The area of your rectangle is {}cm\u00b2".format(area))

The end of the code will print cm² .代码的末尾将打印cm² You can change the large 2 at the end to other numbers for a different result.您可以将末尾的大 2 更改为其他数字以获得不同的结果。 I do not know how to do a lower subscript though.我不知道如何做一个较低的下标。

In Python 3.6+ (mentioned only because the example uses f-strings that are not available in previous versions) named Unicode characters provide an easy to write, easy to read way to do this.在 Python 3.6+ 中(仅提及此示例是因为该示例使用了以前版本中不可用的 f 字符串)命名的 Unicode 字符提供了一种易于编写、易于阅读的方法来执行此操作。 Here is a list.这是一个列表。

Example:例子:

f'\N{GREEK SMALL LETTER GAMMA}={density:.2f} t/m\N{SUPERSCRIPT THREE}'

yields something like产生类似

γ=1.20 t/m³

You could use sympy module that does necessary formatting for you.您可以使用sympy模块为您进行必要的格式化。 It supports many formats such as ascii, unicode, latex, mathml, etc:它支持多种格式,例如 ascii、unicode、latex、mathml 等:

from sympy import pretty_print as pp, latex
from sympy.abc import a, b, n

expr = (a*b)**n
pp(expr) # default
pp(expr, use_unicode=True)
print(latex(expr))
print(expr.evalf(subs=dict(a=2,b=4,n=5)))

Output输出

     n
(a*b) 
     n
(a⋅b) 
$\left(a b\right)^{n}$
32768.0000000000

For those looking for a practical (but a bit imperfect) UTF-8-based solution, implemented using a simple character translation table:对于那些寻找实用(但有点不完美) 基于 UTF-8 的解决方案的人,使用简单的字符转换表实现:

import string

superscript_map = {
    "0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴", "5": "⁵", "6": "⁶",
    "7": "⁷", "8": "⁸", "9": "⁹", "a": "ᵃ", "b": "ᵇ", "c": "ᶜ", "d": "ᵈ",
    "e": "ᵉ", "f": "ᶠ", "g": "ᵍ", "h": "ʰ", "i": "ᶦ", "j": "ʲ", "k": "ᵏ",
    "l": "ˡ", "m": "ᵐ", "n": "ⁿ", "o": "ᵒ", "p": "ᵖ", "q": "۹", "r": "ʳ",
    "s": "ˢ", "t": "ᵗ", "u": "ᵘ", "v": "ᵛ", "w": "ʷ", "x": "ˣ", "y": "ʸ",
    "z": "ᶻ", "A": "ᴬ", "B": "ᴮ", "C": "ᶜ", "D": "ᴰ", "E": "ᴱ", "F": "ᶠ",
    "G": "ᴳ", "H": "ᴴ", "I": "ᴵ", "J": "ᴶ", "K": "ᴷ", "L": "ᴸ", "M": "ᴹ",
    "N": "ᴺ", "O": "ᴼ", "P": "ᴾ", "Q": "Q", "R": "ᴿ", "S": "ˢ", "T": "ᵀ",
    "U": "ᵁ", "V": "ⱽ", "W": "ᵂ", "X": "ˣ", "Y": "ʸ", "Z": "ᶻ", "+": "⁺",
    "-": "⁻", "=": "⁼", "(": "⁽", ")": "⁾"}

trans = str.maketrans(
    ''.join(superscript_map.keys()),
    ''.join(superscript_map.values()))

'The quick brown fox jumps over the lazy dog'.translate(trans)
# ᵀʰᵉ ۹ᵘᶦᶜᵏ ᵇʳᵒʷⁿ ᶠᵒˣ ʲᵘᵐᵖˢ ᵒᵛᵉʳ ᵗʰᵉ ˡᵃᶻʸ ᵈᵒᵍ

As a bonus, here is the subscript counterpart:作为奖励,这里是对应的下标:

subscript_map = {
    "0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄", "5": "₅", "6": "₆",
    "7": "₇", "8": "₈", "9": "₉", "a": "ₐ", "b": "♭", "c": "꜀", "d": "ᑯ",
    "e": "ₑ", "f": "բ", "g": "₉", "h": "ₕ", "i": "ᵢ", "j": "ⱼ", "k": "ₖ",
    "l": "ₗ", "m": "ₘ", "n": "ₙ", "o": "ₒ", "p": "ₚ", "q": "૧", "r": "ᵣ",
    "s": "ₛ", "t": "ₜ", "u": "ᵤ", "v": "ᵥ", "w": "w", "x": "ₓ", "y": "ᵧ",
    "z": "₂", "A": "ₐ", "B": "₈", "C": "C", "D": "D", "E": "ₑ", "F": "բ",
    "G": "G", "H": "ₕ", "I": "ᵢ", "J": "ⱼ", "K": "ₖ", "L": "ₗ", "M": "ₘ",
    "N": "ₙ", "O": "ₒ", "P": "ₚ", "Q": "Q", "R": "ᵣ", "S": "ₛ", "T": "ₜ",
    "U": "ᵤ", "V": "ᵥ", "W": "w", "X": "ₓ", "Y": "ᵧ", "Z": "Z", "+": "₊",
    "-": "₋", "=": "₌", "(": "₍", ")": "₎"}


sub_trans = str.maketrans(
    ''.join(subscript_map.keys()),
    ''.join(subscript_map.values()))

'The quick brown fox jumps over the lazy dog'.translate(sub_trans)
# 'ₜₕₑ ૧ᵤᵢ꜀ₖ ♭ᵣₒwₙ բₒₓ ⱼᵤₘₚₛ ₒᵥₑᵣ ₜₕₑ ₗₐ₂ᵧ ᑯₒ₉'

Again, not perfect, but workable.同样,不完美,但可行。

Since, for no reason I can determine, there is no such thing as a string comprehension in Python, the most straightforward solution I can think of is just joining a list of chars obtained by running your number through str() and a lookup table.因为,我无缘无故地确定,Python 中没有字符串理解这样的东西,所以我能想到的最直接的解决方案就是加入通过 str() 和查找表运行您的数字获得的字符列表。 I see no reason not to just use the unicode string of superscripts as a literal.我认为没有理由不将上标的 unicode 字符串用作文字。 Just subtract the offset of the value of '0' and you have index into the string for your superscript replacement.只需减去 '0' 值的偏移量,您就拥有了用于上标替换的字符串索引。

def superscript(n):
    return "".join(["⁰¹²³⁴⁵⁶⁷⁸⁹"[ord(c)-ord('0')] for c in str(n)]) 

You're using input() , so I imagine this is console-based.您正在使用input() ,所以我想这是基于控制台的。 To that end, you have two options, as previously discussed here .为此,您有两种选择,如之前在此处讨论的。 One is to use a bit of formatting trickery to display the exponents on the line above the actual expansion.一种是使用一些格式化技巧来在实际扩展上方的行上显示指数。 The other is to use these nifty characters, assuming your console supports Unicode:另一种是使用这些漂亮的字符,假设您的控制台支持 Unicode:

⁰¹²³⁴⁵⁶⁷⁸⁹

You're probably going to have to increase the font size by quite a bit for them to be legible, but it's certainly a viable option assuming proper support.您可能必须将字体大小增加很多才能使其清晰易读,但如果有适当的支持,这肯定是一个可行的选择。 Aside from that, though, you mentioned this is a personal learning experience;不过,除此之外,您提到这是个人学习经历; why not combine it with another and learn the simpler aspects of Pygame?为什么不将它与另一个结合起来学习 Pygame 的简单方面呢? It's very straightforward, text manipulation and keyboard events couldn't be simpler, and it's never a wrong step to branch out.它非常简单,文本操作和键盘事件再简单不过了,而且分支永远不会出错。

Unicode character is the solution! Unicode 字符就是解决方案!


There is a very easy way to print superscripts and subscripts using Unicode characters.有一种非常简单的方法可以使用 Unicode 字符打印上标和下标。 Do the following:请执行下列操作:

  • Press alt+f2按 alt+f2
  • Type "charmap"输入“字符图”

On doing so, you'll get tons of characters including subscripts, superscripts, etc. On the bottom left end of the window, you'd see something like 'U-xxxx' where x can be any alpha-numeric character(eg 1,2,A,B..).这样做时,您将获得大量字符,包括下标、上标等。在窗口的左下角,您会看到类似“U-xxxx”的内容,其中 x 可以是任何字母数字字符(例如 1 ,2,A,B...)。

For example:例如:

  • If you want to print a string x^2, you should write the string as:如果你想打印一个字符串 x^2,你应该把字符串写成:

    'x\²', where u00b2 is 'U+00B2' shown in the Character Map. 'x\²',其中 u00b2 是字符映射中显示的 'U+00B2'。

This is how I used Character Map in my tkinter code snippet and it worked without any errors.这就是我在我的 tkinter 代码片段中使用字符映射的方式,它没有任何错误。

You can use this:你可以使用这个:

def conv_to_super(n):
    super=list(map(chr,[8304,185,178,179,8308,8309,8310,8311,8312,8313]))
    st=""
    for i in str(n):
        st+=super[int(i)]
    return(st)

What if you instead of using console text used tile bitmaps?如果您不使用控制台文本而使用平铺位图怎么办? Make an array of tiles.制作一组瓷砖。 Then do the computations on the back end.然后在后端进行计算。 If console text is rigid, switch screen modes and use your own character set.如果控制台文本很僵硬,请切换屏幕模式并使用您自己的字符集。 Just a late night thought.只是一个深夜的想法。

Your Python program is probably running as a console application which can only output characters w/o formatting.您的 Python 程序可能作为控制台应用程序运行,它只能输出没有格式的字符。 The simple answer to your question is "you can't do it".你的问题的简单答案是“你做不到”。

Of course it is possible to write a GUI application, our output to a document format which supports formatting (RTF, HTML, TeX, etc), but this is most likely beyond the scope of the homework problem you are working on.当然,可以编写 GUI 应用程序,将我们的输出转换为支持格式(RTF、HTML、TeX 等)的文档格式,但这很可能超出了您正在处理的作业问题的范围。

As MK already said, you cannot format output on the command line (besides some colors and bold/blinking depending on the terminal).正如 MK 已经说过的,你不能在命令行上格式化输出(除了一些颜色和粗体/闪烁取决于终端)。 However, you could write it in a way that is likely to be understood by your users.但是,您可以以用户可能理解的方式编写它。 If they are from the academic sector, you could use the latex-style way to express superscripts, eg x^2如果是学术界的,可以用latex风格的方式来表示上标,例如x^2

Use pow to make power of something使用pow使某物变得强大

For example:例如:

emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM