32

I am aware of the \xb function in python, but it does not seem to work for me. I am aware that I may need to download a third party module to accomplish this, if so, which one would be best?

I am currently writing a binomial expansion solver, to try and use skills which I am teaching myself. The problem arises when I attempt to display the user input-ed expansion to the use for confirmation. Currently I am having to print the expression like so:

var1 = input("Enter a: ")
var2 = input("Enter b: ")
exponent = input("Enter n: ")

a = int(var1)
b = int(var2)
n = int(exponent)

expression = ('(%(1)dx%(2)d)^%(3)d') %\
{'1' : a, '2' : b, '3' : n}

print(expression)

confirmation = input(str("Is this correctt? Y/N "))

This prints (2x4)^5, whereas I'd prefer the index to be printed as superscript. How can this be done?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Kage93
  • 411
  • 2
  • 6
  • 6
  • 5
    You need to specify your output device/format because that determines *how* the superscript is to be marked up. E.g., in HTML you would output `(2x4)5`. – Peter Rowell Dec 28 '11 at 02:56
  • Don't use [`input()`](http://docs.python.org/library/functions.html#input) on Python 2.x, use [`int(raw_input())`](http://docs.python.org/library/functions.html#raw_input) instead. Otherwise specify that you use Python 3.x. – jfs Dec 28 '11 at 12:54

13 Answers13

33

You need to use a 'format' type thing. Use {}\u00b2".format(area))" and the{}becomes a²`. Here is an example:

print("The area of your rectangle is {}cm\u00b2".format(area))

The end of the code will print cm². You can change the large 2 at the end to other numbers for a different result. I do not know how to do a lower subscript though.

vard
  • 4,057
  • 2
  • 26
  • 46
James
  • 331
  • 1
  • 3
  • 2
  • 8
    > _You can change the large 2 at the end to other numbers for a different result._ This is not true. While `\u00b3` returns `³`, `\u00b4` returns `´`, `\u00b5` returns `µ`. – Eduardo Pignatelli Apr 08 '20 at 16:42
25

In Python 3.6+ (mentioned only because the example uses f-strings that are not available in previous versions) named Unicode characters provide an easy to write, easy to read way to do this. Here is a list.

Example:

f'\N{GREEK SMALL LETTER GAMMA}={density:.2f} t/m\N{SUPERSCRIPT THREE}'

yields something like

γ=1.20 t/m³
jake77
  • 1,892
  • 2
  • 15
  • 22
  • 3
    This actually works since [Python 3.3](https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals). – skrx May 12 '18 at 02:09
  • 2
    No, it doesn't: [since 3.6](https://docs.python.org/3/whatsnew/3.6.html) – jake77 May 14 '18 at 09:04
  • 6
    Not the f-strings, the \N{name} escape sequence. – skrx May 14 '18 at 09:47
  • This seems like a good way but is there a way to use variables with this? i.e. if I have `power = 5` how can I make it print `γ=5.00 t/m⁵`? – Tomerikoo Aug 12 '21 at 13:26
  • does not work in 3.11, I think it's pretty outdated – Aku Jan 12 '23 at 21:01
  • Just fyi for those looking to replace superscripts in strings this works using jake77 example. 'df1.str.replace( r'\N{SUPERSCRIPT TWO}',''',regex =True) – Nick_Jo Jan 17 '23 at 02:23
16

For those looking for a practical (but a bit imperfect) UTF-8-based solution, implemented using a simple character translation table:

import string

superscript_map = {
    "0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴", "5": "⁵", "6": "⁶",
    "7": "⁷", "8": "⁸", "9": "⁹", "a": "ᵃ", "b": "ᵇ", "c": "ᶜ", "d": "ᵈ",
    "e": "ᵉ", "f": "ᶠ", "g": "ᵍ", "h": "ʰ", "i": "ᶦ", "j": "ʲ", "k": "ᵏ",
    "l": "ˡ", "m": "ᵐ", "n": "ⁿ", "o": "ᵒ", "p": "ᵖ", "q": "۹", "r": "ʳ",
    "s": "ˢ", "t": "ᵗ", "u": "ᵘ", "v": "ᵛ", "w": "ʷ", "x": "ˣ", "y": "ʸ",
    "z": "ᶻ", "A": "ᴬ", "B": "ᴮ", "C": "ᶜ", "D": "ᴰ", "E": "ᴱ", "F": "ᶠ",
    "G": "ᴳ", "H": "ᴴ", "I": "ᴵ", "J": "ᴶ", "K": "ᴷ", "L": "ᴸ", "M": "ᴹ",
    "N": "ᴺ", "O": "ᴼ", "P": "ᴾ", "Q": "Q", "R": "ᴿ", "S": "ˢ", "T": "ᵀ",
    "U": "ᵁ", "V": "ⱽ", "W": "ᵂ", "X": "ˣ", "Y": "ʸ", "Z": "ᶻ", "+": "⁺",
    "-": "⁻", "=": "⁼", "(": "⁽", ")": "⁾"}

trans = str.maketrans(
    ''.join(superscript_map.keys()),
    ''.join(superscript_map.values()))

'The quick brown fox jumps over the lazy dog'.translate(trans)
# ᵀʰᵉ ۹ᵘᶦᶜᵏ ᵇʳᵒʷⁿ ᶠᵒˣ ʲᵘᵐᵖˢ ᵒᵛᵉʳ ᵗʰᵉ ˡᵃᶻʸ ᵈᵒᵍ

As a bonus, here is the subscript counterpart:

subscript_map = {
    "0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄", "5": "₅", "6": "₆",
    "7": "₇", "8": "₈", "9": "₉", "a": "ₐ", "b": "♭", "c": "꜀", "d": "ᑯ",
    "e": "ₑ", "f": "բ", "g": "₉", "h": "ₕ", "i": "ᵢ", "j": "ⱼ", "k": "ₖ",
    "l": "ₗ", "m": "ₘ", "n": "ₙ", "o": "ₒ", "p": "ₚ", "q": "૧", "r": "ᵣ",
    "s": "ₛ", "t": "ₜ", "u": "ᵤ", "v": "ᵥ", "w": "w", "x": "ₓ", "y": "ᵧ",
    "z": "₂", "A": "ₐ", "B": "₈", "C": "C", "D": "D", "E": "ₑ", "F": "բ",
    "G": "G", "H": "ₕ", "I": "ᵢ", "J": "ⱼ", "K": "ₖ", "L": "ₗ", "M": "ₘ",
    "N": "ₙ", "O": "ₒ", "P": "ₚ", "Q": "Q", "R": "ᵣ", "S": "ₛ", "T": "ₜ",
    "U": "ᵤ", "V": "ᵥ", "W": "w", "X": "ₓ", "Y": "ᵧ", "Z": "Z", "+": "₊",
    "-": "₋", "=": "₌", "(": "₍", ")": "₎"}


sub_trans = str.maketrans(
    ''.join(subscript_map.keys()),
    ''.join(subscript_map.values()))

'The quick brown fox jumps over the lazy dog'.translate(sub_trans)
# 'ₜₕₑ ૧ᵤᵢ꜀ₖ ♭ᵣₒwₙ բₒₓ ⱼᵤₘₚₛ ₒᵥₑᵣ ₜₕₑ ₗₐ₂ᵧ ᑯₒ₉'

Again, not perfect, but workable.

norok2
  • 25,683
  • 4
  • 73
  • 99
  • The number superscripts are written at different heights. For example 0 is higher than 1 (at least when using ipycanvas) – Daniel Aug 11 '20 at 08:48
  • @Daniel The numbers are actually supported by UTF-8. So, if there is a rendering issue, it is likely to be with the fonts. Perhaps you could try different fonts. – norok2 Aug 11 '20 at 09:23
  • I see them in line here in the normal text: ⁰¹²³⁴⁵⁶⁷⁸⁹ but not in the code: `⁰¹²³⁴⁵⁶⁷⁸⁹` where `123` seems slightly larger than the others. – norok2 Aug 11 '20 at 12:12
  • 1
    Lovely. Thanks @norck2 – Zanoldor Sep 06 '20 at 14:24
  • @norok2, strangely, I don't see the normal text symbols you posted in line (1, 2 and 3 are a bit lower). Probably a font issue as you said. – Daniel Sep 29 '20 at 09:05
  • How do I make both subscript and superscript text appear in the same spot? i.e. one character directly above the other. – Frak Nov 30 '20 at 02:38
  • @frakman1 UTF-8 was not really designed for this. While some fonts may support this via OpenType using the unicode private area, you should really look into another option. See also https://en.wikipedia.org/wiki/Subscript_and_superscript – norok2 Nov 30 '20 at 08:01
  • @norok2. Thanks. I just thought this would be a common use-case for scientific formulas and [chemistry elements](https://4.bp.blogspot.com/-RRRA7MTNJcA/V1a46M2VT1I/AAAAAAAAAFA/oaPGsMySnakU-MfNOcQjC9TAV0d_oNFRgCLcB/s1600/subscript-and-superscript.png) – Frak Dec 01 '20 at 14:19
  • The problem is that the different superscripts and subscripts unfortunately reside in different unicode blocks. Many fonts struggle with that. For instance, the superscripts of 1, 2 and 3 are in the "Latin-1 Supplement" block while the superscripts of 0, 4, 5, 6, 7, 8 and 9 are part of the "Superscripts and Subscripts" block. As letters are added, it becomes even more complicated as you can see above. – Joooeey Jan 23 '23 at 09:34
13

You could use sympy module that does necessary formatting for you. It supports many formats such as ascii, unicode, latex, mathml, etc:

from sympy import pretty_print as pp, latex
from sympy.abc import a, b, n

expr = (a*b)**n
pp(expr) # default
pp(expr, use_unicode=True)
print(latex(expr))
print(expr.evalf(subs=dict(a=2,b=4,n=5)))

Output

     n
(a*b) 
     n
(a⋅b) 
$\left(a b\right)^{n}$
32768.0000000000
jfs
  • 399,953
  • 195
  • 994
  • 1,670
8

Since, for no reason I can determine, there is no such thing as a string comprehension in Python, the most straightforward solution I can think of is just joining a list of chars obtained by running your number through str() and a lookup table. I see no reason not to just use the unicode string of superscripts as a literal. Just subtract the offset of the value of '0' and you have index into the string for your superscript replacement.

def superscript(n):
    return "".join(["⁰¹²³⁴⁵⁶⁷⁸⁹"[ord(c)-ord('0')] for c in str(n)]) 
Greg Conner
  • 81
  • 1
  • 2
6

Unicode character is the solution!


There is a very easy way to print superscripts and subscripts using Unicode characters. Do the following:

  • Press Alt+F2
  • Type "charmap"

On doing so, you'll get tons of characters including subscripts, superscripts, etc. On the bottom left end of the window, you'd see something like 'U-xxxx' where x can be any alpha-numeric character(e.g 1,2,A,B..).

For example:

  • If you want to print a string like , you should write the string as:

    'x\u00b2', where u00b2 is 'U+00B2' shown in the Character Map.

This is how I used Character Map in my tkinter code snippet and it worked without any errors.

Neuron
  • 5,141
  • 5
  • 38
  • 59
TheSHETTY-Paradise
  • 1,024
  • 2
  • 9
  • 19
  • 1
    This *must* be for some single platform only. Windows? If it is: you can only find those characters in fonts that support them (and I'd then advise using Arial MS Unicode). But since OP wants to create a console based program, those same characters must also be available in the console font. – Jongware Nov 29 '18 at 21:19
  • 1
    I use Ubuntu 18.04 and it works here, I'm unaware of windows – TheSHETTY-Paradise Dec 02 '18 at 03:45
4

You're using input(), so I imagine this is console-based. To that end, you have two options, as previously discussed here. One is to use a bit of formatting trickery to display the exponents on the line above the actual expansion. The other is to use these nifty characters, assuming your console supports Unicode:

⁰¹²³⁴⁵⁶⁷⁸⁹

You're probably going to have to increase the font size by quite a bit for them to be legible, but it's certainly a viable option assuming proper support. Aside from that, though, you mentioned this is a personal learning experience; why not combine it with another and learn the simpler aspects of Pygame? It's very straightforward, text manipulation and keyboard events couldn't be simpler, and it's never a wrong step to branch out.

Community
  • 1
  • 1
ranksrejoined
  • 1,229
  • 9
  • 9
1

You can use this:

def conv_to_super(n):
    super=list(map(chr,[8304,185,178,179,8308,8309,8310,8311,8312,8313]))
    st=""
    for i in str(n):
        st+=super[int(i)]
    return(st)

Supriyo Halder
  • 200
  • 1
  • 7
0

You can, instead of using console text, use tile bitmaps. Make an array of tiles. Then do the computations on the back end. If console text is rigid, switch screen modes and use your own character set. Just a late night thought.

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Damon
  • 1
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 23 '21 at 08:42
  • I recommend against rhetoric questions in answers. They risk being misunderstood as not an answer at all. You are trying to answer the question at the top of this page, aren't you? Otherwise please delete this post. – Yunnosch Nov 19 '21 at 06:42
0

This will convert superscripts of any size to unicode characters: (p is supposed to be an int)

    def superscript(p):
        superscripts = ["⁰", "¹", "²", "³", "⁴", "⁵", "⁶", "⁷", "⁸", "⁹"]
        return ''.join([superscripts[int(char)] for char in str(p)])
Jakub Orsula
  • 75
  • 2
  • 10
0

Your Python program is probably running as a console application which can only output characters w/o formatting. The simple answer to your question is "you can't do it".

Of course it is possible to write a GUI application, our output to a document format which supports formatting (RTF, HTML, TeX, etc), but this is most likely beyond the scope of the homework problem you are working on.

MK.
  • 33,605
  • 18
  • 74
  • 111
  • Thanks for the reply, but no, I intend to write the barebones of the program without a GUI then once I am satisfied that everything works, I will create a GUI for it. I plan on using tkinter for my GUI, would it be possible using tkinter then? If not, which module would be suitable? – Kage93 Dec 28 '11 at 03:02
0

As MK already said, you cannot format output on the command line (besides some colors and bold/blinking depending on the terminal). However, you could write it in a way that is likely to be understood by your users. If they are from the academic sector, you could use the latex-style way to express superscripts, e.g. x^2

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
-4

Use pow to make power of something

For example:

emi = (p * r * pow(1 + r, t)) / (pow(1 + r, t) - 1)
user229044
  • 232,980
  • 40
  • 330
  • 338