1

I have a float number stored as scientific notation in a tuple:

correlation = (1,1.1884423896339773e-06)

I want to reformat that float (correlation[1]) into the following format, to be plotted as a string in a plot:

1.19 * 10^-6         # '-6' should be in superscript actually here

However, I am getting an SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-4: truncated \uXXXX escape

lsF = str(correlation[1])
ePos = lsF.find("e")
if (ePos):
    base = float(lsF[:ePos])
    exponent = int(lsF[ePos+1:])
else:
    base = float(lsF)
    exponent = 0
print(round(base, 2), " * 10", eval(r'"\u00b' + str(exponent) + '"'), sep="")

When my exponent is positive, this works well.

mozway
  • 194,879
  • 13
  • 39
  • 75
rororo
  • 815
  • 16
  • 31
  • I didn't understand which part of this code is supposed to make superscript. – mkrieger1 Jan 24 '22 at 10:56
  • The last one (`print`), the code above is to extract the exponent and the base (I'm happy for improvements here too!) – rororo Jan 24 '22 at 10:57
  • What do you mean by "it works well"? If I use `base = 3.4; exponent = 5`, it prints `3.4 * 10µ`, but nothing is in superscript. – mkrieger1 Jan 24 '22 at 10:58
  • oh sh*t, I only tried ` exponent = 2 `, and that did work :( – rororo Jan 24 '22 at 11:00
  • 2
    Does this answer your question? [How do you print superscript in Python?](https://stackoverflow.com/questions/8651361/how-do-you-print-superscript-in-python) – Jay Jan 24 '22 at 11:01

1 Answers1

2

The issue with the superscript numbers is that the UTF-8 codes are not contiguous, you need a translation table.

Here is one way to do it with the help of f-strings:

def scientific_superscript(num, digits=2):
    base, exponent = f'{num:.{digits}e}'.split('e')
    d = dict(zip('-+0123456789','⁻⁺⁰¹²³⁴⁵⁶⁷⁸⁹'))
    return f'{base}⋅10{"".join(d.get(x, x) for x in  exponent)}'

scientific_superscript(1.1884423896339773e-06)
# '1.19⋅10⁻⁰⁶'

scientific_superscript(3.141e123)
# '3.14⋅10⁺¹²³'
blacklisting characters:

example for 0 and +

def scientific_superscript(num, digits=2):
    base, exponent = f'{num:.{digits}e}'.split('e')
    d = dict(zip('-+0123456789','⁻⁺⁰¹²³⁴⁵⁶⁷⁸⁹'))
    return f'{base}⋅10{"".join(d.get(x, x) for x in exponent.lstrip("0+"))}'

scientific_superscript(3.141e3)
# '3.14⋅10³'

scientific_superscript(1e103)
# '1.00⋅10¹⁰³'
mozway
  • 194,879
  • 13
  • 39
  • 75