Superscript for a variable

Question:

I want to print out a variable as a superscript. I have done a lot of research and lots of people use the method of Unicode. Which is something like print("wordu00b2") where the 2 will be in superscript. However, I want to replace the 2 with a variable. These are the methods I have tried

print("wordu00b{variable}")
print("wordu00b{}".format(variable))
print("wordu00b%s" % variable)

and of course with the back slash

print("wordu00b{variable}")
print("wordu00b{}".format(variable))
print("wordu00b%s" % variable)

As well, I have also tried something like

variable = variable.decode(u"u00b")

None of the above worked as I kept getting

(unicode error) 'unicodeescape' codec can't decode bytes in position 5-9: truncated uXXXX escape

Some help will be appreciated.

Asked By: Coco Liliace

||

Answers:

The escape code u00b2 is a single character; you want something like

>>> print(eval(r'"u00b' + str(2) + '"'))
²

Less convolutedly,

>>> print(chr(0x00b2))
²

This only works for superscript 2 and 3, though; the other Unicode superscripts are in a different code block.

>>> for i in range(10):
...   if i == 1:
...     print(chr(0x00b9))
...   elif 2 <= i <= 3:
...     print(chr(0x00b0 + i))
...   else:
...     print(chr(0x2070 + i))
⁰
¹
²
³
⁴
⁵
⁶
⁷
⁸
⁹
Answered By: tripleee

If you want your entire variable to be superscripted you have to use the % format. If you try to .format() it, it will only superscript the first letter or number because it uses brackets to group numbers inside of the $$.

I wrote my code like this:

print(r'$y=%f*x^{%f}$' % (var_A, var_B)

This way you do not have to call Unicode. I found this method worked for graph titles, axis titles, graph legends.

I hope this helps!

Answered By: Deryc