Replace every caret with a superscript in a python string

Question:

I want to replace every caret character with a unicode superscript, for nicer printing of equations in python. My problem is, every caret may be followed by a different exponent value, so in the unicode string u’u00b*’, the * wildcard needs to be the exponent I want to print in the string. I figured some regex would work for this, but my experience with that is very little.

For example, supposed I have a string
“x^3-x^2″
, I would then want this to be converted to the unicode string
u”xu00b3-xu00b2”

Asked By: Jack Bates

||

Answers:

You can use re.sub and str.translate to catch exponents and change them to unicode superscripts.

import re

def to_superscript(num):
    transl = str.maketrans('1234567890', '¹²³⁴⁵⁶⁷⁸⁹⁰')
    return num.translate(transl)

s = 'x^3-x^2'

out = re.sub('^s*(d+)', lambda m: to_superscript(m[1]), s)

print(out)

Output

x³-x²
Answered By: Olivier Melançon
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.