将数字字符串转换为上标

roo*_*oot 6 python unicode

我需要将数字字符串转换为上标,是否有更好的(内置)方式呢?

def to_sup(s):
    sups={u'1': u'\xb9', 
          u'0': u'\u2070',
          u'3': u'\xb3', 
          u'2': u'\xb2',
          u'5': u'\u2075',
          u'4': u'\u2074',
          u'7': u'\u2077',
          u'6': u'\u2076',
          u'9': u'\u2079',
          u'8': u'\u2078'}
    if s.isdigit():
        return ''.join([sups[i] for i in s])
print to_sup('0123')
Run Code Online (Sandbox Code Playgroud)

输出:

?¹²³
Run Code Online (Sandbox Code Playgroud)

Eri*_*ric 8

你的方式有点不正确.更好的是:

def to_sup(s):
    sups = {u'0': u'\u2070',
            u'1': u'\xb9',
            u'2': u'\xb2',
            u'3': u'\xb3',
            u'4': u'\u2074',
            u'5': u'\u2075',
            u'6': u'\u2076',
            u'7': u'\u2077',
            u'8': u'\u2078',
            u'9': u'\u2079'}

    return ''.join(sups.get(char, char) for char in s)  # lose the list comprehension
Run Code Online (Sandbox Code Playgroud)

s.isdigit() 只检查第一个字母,这可能没有意义.

如果由于某种原因你想要一个单行:

u''.join(dict(zip(u"0123456789", u"?¹²³??????")).get(c, c) for c in s)
Run Code Online (Sandbox Code Playgroud)