Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert numeric strings to superscript

Tags:

python

unicode

I need convert numeric strings to superscript, is there a better (built-in) way of doing it?

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

Output:

⁰¹²³
like image 640
root Avatar asked Dec 14 '12 09:12

root


People also ask

What is the command for superscript?

To make text appear slightly above (superscript) or below (subscript) your regular text, you can use keyboard shortcuts. Select the character that you want to format. For superscript, press Ctrl, Shift, and the Plus sign (+) at the same time. For subscript, press Ctrl and the Equal sign (=) at the same time.

How to add both superscript and subscript in Excel?

Format text values as superscript or subscript Select characters in a cell or cell range that you'd like to format. On the Home tab, in the Font group, click the Font Settings dialog box launcher. Press CTRL+1. Under Effects, check the Superscript or Subscript box, and click OK.

What is a subscript number?

A superscript or subscript is a number, figure, symbol, or indicator that is smaller than the normal line of type and is set slightly above it (superscript) or below it (subscript).


1 Answers

Your way is slightly incorrect. Better would be:

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

s.isdigit() will only check the first letter, which probably doesn't make sense.

If for some reason you want a one-liner:

u''.join(dict(zip(u"0123456789", u"⁰¹²³⁴⁵⁶⁷⁸⁹")).get(c, c) for c in s)
like image 200
Eric Avatar answered Sep 30 '22 13:09

Eric