首页 > 解决方案 > 如何打印格式指数

问题描述

我想知道是否有任何方法可以像我们在 x2 这样的数学中那样以字符串格式打印 x^2。其中 2 是 x 右上角的指数形式。

例子

标签: pythonpython-3.x

解决方案


怎么样:

def stringify_exponent(n, m):
    superscripted = "".join(_DIGITS[int(d)] for d in str(m))
    return f"{n}{superscripted}"


_DIGITS = [
    "\N{superscript zero}",
    "\N{superscript one}",
    "\N{superscript two}",
    "\N{superscript three}",
    "\N{superscript four}",
    "\N{superscript five}",
    "\N{superscript six}",
    "\N{superscript seven}",
    "\N{superscript eight}",
    "\N{superscript nine}"
]


if __name__ == "__main__":
    print(stringify_exponent(10, 2))
    print(stringify_exponent(2, 1024))

印刷:

10²
2¹⁰²⁴

推荐阅读