在Python 3.3中,有什么方法可以在打印时使字符串中的部分文本成为下标吗?
例如H2(H,然后是下标 2)
如果您只关心数字,则可以使用str.maketrans() https://docs.python.org/3/library/stdtypes.html#str.maketrans and str.translate() https://docs.python.org/3/library/stdtypes.html#str.translate方法:
example_string = "A0B1C2D3E4F5G6H7I8J9"
SUB = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
SUP = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
print(example_string.translate(SUP))
print(example_string.translate(SUB))
这将输出:
A⁰B¹C²D³E⁴F⁵G⁶H⁷I⁸J⁹
A₀B₁C₂D₃E₄F₅G₆H₇I₈J₉
请注意,这在 Python 2 中不起作用 - 请参阅Python 2 maketrans() 函数不适用于 Unicode https://stackoverflow.com/q/30108869解释为什么会出现这种情况,以及如何解决这个问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)