Repository: hgrecco/pint

Issue:
Turn off latex rendering in jupyter notebooks
I have been wrapping some pretty large numpy arrays with pint lately. Unfortunately, viewing these arrays with mathjax rendering ends up crashing my web browser. I searched the docs for a way to turn off the default rendering, but I could not find anything. Is there an easy way to do this?

Discussion:
keewis: this would definitely be a big improvement of the expanded HTML repr of xarray objects (I never really looked at the repr of quantities in a notebook so I can't comment on that), although the repr for big `numpy` arrays looks a bit strange (to fix that, I guess numpy needs its own `_repr_html_`?). :+1: for the new HTML repr

To properly format the collapsed or text repr we'd need to first modify `xarray`, so I guess we can ignore them for now.
jthielen: Also, just to add a note here: assuming the `_repr_short_` or `_repr_inline_` of https://github.com/pydata/xarray/pull/4248 goes through as brought up by @keewis, that would be important to add to Pint here or in a follow-up PR.
jthielen: Pinging @hgrecco for your thoughts on this in particular as maintainer, since it's been three weeks since the initial inquiry? Thanks!
keewis: I've been wondering whether the `_repr_inline_` would be a good fit for `pint`, or whether it should be provided by `pint-xarray`. Until it is adopted by other packages this would be something specific to `xarray`, so it would probably be better to implement in `pint-xarray`. However, that would mean we're relying on monkeypatching, which is generally not a good idea. Thoughts?
jthielen: @keewis That's a good point.

I wouldn't be too concerned about monkeypatching for something like `_repr_inline_`, since it is a single method that can be injected into the global Quantity class, and as you said, is just used in this one place for xarray at the moment. I guess what it comes down to for me is: do we expect all users of `xarray` with `pint` to be always using `pint-xarray`? If so, then it definitely seems reasonable to monkeypatch this in `pint-xarray`. If not, it could be surprising behavior to the unaware user to have "nice" inline reprs when `pint-xarray` is available/imported and "ugly" reprs when not.

In any case, since it isn't quite the simple thing I initially thought, I think it would be best to defer implementation of `_repr_inline_` to another PR (either direct implementation in Pint or monkeypatch in pint-xarray) so as to not cloud the more general HTML repr discussion here.
keewis: agreed. I'd say let's implement this in `pint-xarray` for now and if desired we can move it to `pint` later.
jthielen: Just wanted to ping @hgrecco again on this. I'll be working on some xarray & Pint integration docs for MetPy in the near future, and it would be great to have this in (or at have the general direction approved) by then.
hgrecco: Sorry for the late reply,. pandemic times! I was also never really happy by the way pint represents this. So I agree with the change as long as an scalar is kept "normal" (as you also showed)!. Thanks for the PR (and pinging again!
jthielen: > Sorry for the late reply,. pandemic times! I was also never really happy by the way pint represents this. So I agree with the change as long as an scalar is kept "normal" (as you also showed)!. Thanks for the PR (and pinging again!

Sounds good, I'll work on the tests and then mark as ready for review!
jthielen: Hopefully I've finally gotten the uncertainties stuff fixed, so (assuming it is) this should be ready for review and merge.

Patch:
diff --git a/.gitignore b/.gitignore
index d2fddea..610ed68 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,3 +27,6 @@ test/
 
 # test csv which should be user generated
 notebooks/pandas_test.csv
+
+# dask stuff
+dask-worker-space
diff --git a/CHANGES b/CHANGES
index 9922eda..13947da 100644
--- a/CHANGES
+++ b/CHANGES
@@ -4,6 +4,9 @@ Pint Changelog
 0.15 (unreleased)
 -----------------
 
+- Change `Quantity` and `Unit` HTML (i.e., Jupyter notebook) repr away from LaTeX to a
+  simpler, more performant pretty-text and table based repr inspired by Sparse and Dask.
+  (Issue #654)
 - Implement Dask collection interface to support Pint Quantity wrapped Dask arrays.
 - Started automatically testing examples in the documentation
 - Fixed right operand power for dimensionless Quantity to reflect numpy behavior. (Issue #1136)
diff --git a/docs/tutorial.rst b/docs/tutorial.rst
index e473ac4..1c64c4e 100644
--- a/docs/tutorial.rst
+++ b/docs/tutorial.rst
@@ -319,10 +319,10 @@ Pint also supports `f-strings`_ from python>=3.6 :
    >>> print(f'The str is {accel:~.3e}')
    The str is 1.300e+00 m / s ** 2
    >>> print(f'The str is {accel:~H}')      # HTML format (displays well in Jupyter)
-   The str is \[1.3\ m/{s}^{2}\]
+   The str is 1.3 m/s<sup>2</sup>
 
-But Pint also extends the standard formatting capabilities for unicode and
-LaTeX representations:
+But Pint also extends the standard formatting capabilities for unicode, LaTeX, and HTML
+representations:
 
 .. doctest::
 
@@ -335,7 +335,7 @@ LaTeX representations:
    'The LaTeX representation is 1.3\\ \\frac{\\mathrm{meter}}{\\mathrm{second}^{2}}'
    >>> # HTML print - good for Jupyter notebooks
    >>> 'The HTML representation is {:H}'.format(accel)
-   'The HTML representation is \\[1.3\\ meter/{second}^{2}\\]'
+   'The HTML representation is 1.3 meter/second<sup>2</sup>'
 
 If you want to use abbreviated unit names, prefix the specification with `~`:
 
diff --git a/pint/formatting.py b/pint/formatting.py
index 495dfec..3cc7643 100644
--- a/pint/formatting.py
+++ b/pint/formatting.py
@@ -95,7 +95,7 @@ _FORMATS = {
         "single_denominator": True,
         "product_fmt": r" ",
         "division_fmt": r"{}/{}",
-        "power_fmt": "{{{}}}^{{{}}}",  # braces superscript whole exponent
+        "power_fmt": r"{}<sup>{}</sup>",
         "parentheses_fmt": r"({})",
     },
     "": {  # Default format.
@@ -270,12 +270,8 @@ def format_unit(unit, spec, **kwspec):
             (r"\mathrm{{{}}}".format(u.replace("_", r"\_")), p) for u, p in unit.items()
         ]
         return formatter(rm, **fmt).replace("[", "{").replace("]", "}")
-    elif spec == "H":
-        # HTML (Jupyter Notebook)
-        rm = [(u.replace("_", r"\_"), p) for u, p in unit.items()]
-        return formatter(rm, **fmt)
     else:
-        # Plain text
+        # HTML and Text
         return formatter(unit.items(), **fmt)
 
 
diff --git a/pint/measurement.py b/pint/measurement.py
index 826253f..1da1b64 100644
--- a/pint/measurement.py
+++ b/pint/measurement.py
@@ -147,7 +147,7 @@ class Measurement(Quantity):
         if "L" in newspec and "S" in newspec:
             mag = mag.replace("(", r"\left(").replace(")", r"\right)")
 
-        if "L" in newspec or "H" in spec:
+        if "L" in newspec:
             space = r"\ "
         else:
             space = " "
@@ -158,14 +158,10 @@ class Measurement(Quantity):
 
         if "H" in spec:
             # Fix exponential format
-            mag = re.sub(r"\)e\+0?(\d+)", r")×10^{\1}", mag)
-            mag = re.sub(r"\)e-0?(\d+)", r")×10^{-\1}", mag)
+            mag = re.sub(r"\)e\+0?(\d+)", r")×10<sup>\1</sup>", mag)
+            mag = re.sub(r"\)e-0?(\d+)", r")×10<sup>-\1</sup>", mag)
 
-            assert ustr[:2] == r"\["
-            assert ustr[-2:] == r"\]"
-            return r"\[" + mag + space + ustr[2:]
-        else:
-            return mag + space + ustr
+        return mag + space + ustr
 
 
 _Measurement = Measurement
diff --git a/pint/quantity.py b/pint/quantity.py
index 66642a3..5d6ac46 100644
--- a/pint/quantity.py
+++ b/pint/quantity.py
@@ -47,7 +47,6 @@ from .errors import (
 from .formatting import (
     _pretty_fmt_exponent,
     ndarray_to_latex,
-    ndarray_to_latex_parts,
     remove_custom_flags,
     siunitx_format_unit,
 )
@@ -66,6 +65,7 @@ from .util import (
     SharedRegistryObject,
     UnitsContainer,
     infer_base_unit,
+    iterable,
     logger,
     to_units_container,
 )
@@ -311,11 +311,6 @@ class Quantity(PrettyIPython, SharedRegistryObject):
 
         spec = spec or self.default_format
 
-        if "L" in spec:
-            allf = plain_allf = r"{}\ {}"
-        else:
-            allf = plain_allf = "{} {}"
-
         # If Compact is selected, do it at the beginning
         if "#" in spec:
             spec = spec.replace("#", "")
@@ -323,36 +318,65 @@ class Quantity(PrettyIPython, SharedRegistryObject):
         else:
             obj = self
 
-        # the LaTeX siunitx code
+        if "L" in spec:
+            allf = plain_allf = r"{}\ {}"
+        elif "H" in spec:
+            allf = plain_allf = "{} {}"
+            if iterable(obj.magnitude):
+                # Use HTML table instead of plain text template for array-likes
+                allf = (
+                    "<table><tbody>"
+                    "<tr><th>Magnitude</th>"
+                    "<td style='text-align:left;'>{}</td></tr>"
+                    "<tr><th>Units</th><td style='text-align:left;'>{}</td></tr>"
+                    "</tbody></table>"
+                )
+        else:
+            allf = plain_allf = "{} {}"
+
         if "Lx" in spec:
+            # the LaTeX siunitx code
             spec = spec.replace("Lx", "")
             # TODO: add support for extracting options
             opts = ""
             ustr = siunitx_format_unit(obj.units)
             allf = r"\SI[%s]{{{}}}{{{}}}" % opts
-        elif "H" in spec:
-            ustr = format(obj.units, spec)
-            assert ustr[:2] == r"\["
-            assert ustr[-2:] == r"\]"
-            ustr = ustr[2:-2]
-            allf = r"\[{}\ {}\]"
         else:
+            # Hand off to unit formatting
             ustr = format(obj.units, spec)
 
         mspec = remove_custom_flags(spec)
-        if isinstance(self.magnitude, ndarray):
+        if "H" in spec:
+            # HTML formatting
+            if hasattr(obj.magnitude, "_repr_html_"):
+                # If magnitude has an HTML repr, nest it within Pint's
+                mstr = obj.magnitude._repr_html_()
+            else:
+                if isinstance(self.magnitude, ndarray):
+                    # Use custom ndarray text formatting with monospace font
+                    formatter = "{{:{}}}".format(mspec)
+                    with printoptions(formatter={"float_kind": formatter.format}):
+                        mstr = (
+                            "<pre>"
+                            + format(obj.magnitude).replace("\n", "<br>")
+                            + "</pre>"
+                        )
+                elif not iterable(obj.magnitude):
+                    # Use plain text for scalars
+                    mstr = format(obj.magnitude, mspec)
+                else:
+                    # Use monospace font for other array-likes
+                    mstr = (
+                        "<pre>"
+                        + format(obj.magnitude, mspec).replace("\n", "<br>")
+                        + "</pre>"
+                    )
+        elif isinstance(self.magnitude, ndarray):
             if "L" in spec:
+                # Use ndarray LaTeX special formatting
                 mstr = ndarray_to_latex(obj.magnitude, mspec)
-            elif "H" in spec:
-                allf = r"\[{} {}\]"
-                # this is required to have the magnitude and unit in the same line
-                parts = ndarray_to_latex_parts(obj.magnitude, mspec)
-
-                if len(parts) > 1:
-                    return "\n".join(allf.format(part, ustr) for part in parts)
-
-                mstr = parts[0]
             else:
+                # Use custom ndarray text formatting
                 formatter = "{{:{}}}".format(mspec)
                 with printoptions(formatter={"float_kind": formatter.format}):
                     mstr = format(obj.magnitude).replace("\n", "")
@@ -361,13 +385,14 @@ class Quantity(PrettyIPython, SharedRegistryObject):
 
         if "L" in spec:
             mstr = self._exp_pattern.sub(r"\1\\times 10^{\2\3}", mstr)
-        elif "H" in spec:
-            mstr = self._exp_pattern.sub(r"\1×10^{\2\3}", mstr)
-        elif "P" in spec:
+        elif "H" in spec or "P" in spec:
             m = self._exp_pattern.match(mstr)
+            _exp_formatter = (
+                _pretty_fmt_exponent if "P" in spec else lambda s: f"<sup>{s}</sup>"
+            )
             if m:
                 exp = int(m.group(2) + m.group(3))
-                mstr = self._exp_pattern.sub(r"\1×10" + _pretty_fmt_exponent(exp), mstr)
+                mstr = self._exp_pattern.sub(r"\1×10" + _exp_formatter(exp), mstr)
 
         if allf == plain_allf and ustr.startswith("1 /"):
             # Write e.g. "3 / s" instead of "3 1 / s"
diff --git a/pint/unit.py b/pint/unit.py
index 25084b4..f09f39e 100644
--- a/pint/unit.py
+++ b/pint/unit.py
@@ -91,10 +91,6 @@ class Unit(PrettyIPython, SharedRegistryObject):
         else:
             units = self._units
 
-        if "H" in spec:
-            # HTML / Jupyter Notebook
-            return r"\[" + format(units, spec).replace(" ", r"\ ") + r"\]"
-
         return format(units, spec)
 
     def format_babel(self, spec="", **kwspec):


Test patch:
diff --git a/pint/testsuite/test_measurement.py b/pint/testsuite/test_measurement.py
index 78d48a7..b5acff0 100644
--- a/pint/testsuite/test_measurement.py
+++ b/pint/testsuite/test_measurement.py
@@ -48,13 +48,13 @@ class TestMeasurement(QuantityTestCase):
             ("{!r}", "<Measurement(4.0, 0.1, second ** 2)>"),
             ("{:P}", "(4.00 ± 0.10) second²"),
             ("{:L}", r"\left(4.00 \pm 0.10\right)\ \mathrm{second}^{2}"),
-            ("{:H}", r"\[(4.00 &plusmn; 0.10)\ {second}^{2}\]"),
+            ("{:H}", "(4.00 &plusmn; 0.10) second<sup>2</sup>"),
             ("{:C}", "(4.00+/-0.10) second**2"),
             ("{:Lx}", r"\SI{4.00 +- 0.10}{\second\squared}"),
             ("{:.1f}", "(4.0 +/- 0.1) second ** 2"),
             ("{:.1fP}", "(4.0 ± 0.1) second²"),
             ("{:.1fL}", r"\left(4.0 \pm 0.1\right)\ \mathrm{second}^{2}"),
-            ("{:.1fH}", r"\[(4.0 &plusmn; 0.1)\ {second}^{2}\]"),
+            ("{:.1fH}", "(4.0 &plusmn; 0.1) second<sup>2</sup>"),
             ("{:.1fC}", "(4.0+/-0.1) second**2"),
             ("{:.1fLx}", r"\SI{4.0 +- 0.1}{\second\squared}"),
         ):
@@ -70,7 +70,7 @@ class TestMeasurement(QuantityTestCase):
             ("{:.3uS}", "0.2000(100) second ** 2"),
             ("{:.3uSP}", "0.2000(100) second²"),
             ("{:.3uSL}", r"0.2000\left(100\right)\ \mathrm{second}^{2}"),
-            ("{:.3uSH}", r"\[0.2000(100)\ {second}^{2}\]"),
+            ("{:.3uSH}", "0.2000(100) second<sup>2</sup>"),
             ("{:.3uSC}", "0.2000(100) second**2"),
         ):
             with self.subTest(spec):
@@ -84,7 +84,7 @@ class TestMeasurement(QuantityTestCase):
             ("{:.3u}", "(0.2000 +/- 0.0100) second ** 2"),
             ("{:.3uP}", "(0.2000 ± 0.0100) second²"),
             ("{:.3uL}", r"\left(0.2000 \pm 0.0100\right)\ \mathrm{second}^{2}"),
-            ("{:.3uH}", r"\[(0.2000 &plusmn; 0.0100)\ {second}^{2}\]"),
+            ("{:.3uH}", "(0.2000 &plusmn; 0.0100) second<sup>2</sup>"),
             ("{:.3uC}", "(0.2000+/-0.0100) second**2"),
             ("{:.3uLx}", r"\SI{0.2000 +- 0.0100}{\second\squared}",),
             ("{:.1uLx}", r"\SI{0.20 +- 0.01}{\second\squared}"),
@@ -101,7 +101,7 @@ class TestMeasurement(QuantityTestCase):
             ("{:.1u%}", "(20 +/- 1)% second ** 2"),
             ("{:.1u%P}", "(20 ± 1)% second²"),
             ("{:.1u%L}", r"\left(20 \pm 1\right) \%\ \mathrm{second}^{2}"),
-            ("{:.1u%H}", r"\[(20 &plusmn; 1)%\ {second}^{2}\]"),
+            ("{:.1u%H}", "(20 &plusmn; 1)% second<sup>2</sup>"),
             ("{:.1u%C}", "(20+/-1)% second**2"),
         ):
             with self.subTest(spec):
@@ -117,7 +117,7 @@ class TestMeasurement(QuantityTestCase):
                 "{:.1ueL}",
                 r"\left(2.0 \pm 0.1\right) \times 10^{-1}\ \mathrm{second}^{2}",
             ),
-            ("{:.1ueH}", r"\[(2.0 &plusmn; 0.1)×10^{-1}\ {second}^{2}\]"),
+            ("{:.1ueH}", "(2.0 &plusmn; 0.1)×10<sup>-1</sup> second<sup>2</sup>"),
             ("{:.1ueC}", "(2.0+/-0.1)e-01 second**2"),
         ):
             with self.subTest(spec):
@@ -132,7 +132,7 @@ class TestMeasurement(QuantityTestCase):
             ("{!r}", "<Measurement(4e+20, 1e+19, second ** 2)>"),
             ("{:P}", "(4.00 ± 0.10)×10²⁰ second²"),
             ("{:L}", r"\left(4.00 \pm 0.10\right) \times 10^{20}\ \mathrm{second}^{2}"),
-            ("{:H}", r"\[(4.00 &plusmn; 0.10)×10^{20}\ {second}^{2}\]"),
+            ("{:H}", "(4.00 &plusmn; 0.10)×10<sup>20</sup> second<sup>2</sup>"),
             ("{:C}", "(4.00+/-0.10)e+20 second**2"),
             ("{:Lx}", r"\SI{4.00 +- 0.10 e+20}{\second\squared}"),
         ):
@@ -149,7 +149,7 @@ class TestMeasurement(QuantityTestCase):
                 "{:L}",
                 r"\left(4.00 \pm 0.10\right) \times 10^{-20}\ \mathrm{second}^{2}",
             ),
-            ("{:H}", r"\[(4.00 &plusmn; 0.10)×10^{-20}\ {second}^{2}\]"),
+            ("{:H}", "(4.00 &plusmn; 0.10)×10<sup>-20</sup> second<sup>2</sup>"),
             ("{:C}", "(4.00+/-0.10)e-20 second**2"),
             ("{:Lx}", r"\SI{4.00 +- 0.10 e-20}{\second\squared}"),
         ):
diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py
index fa18fe8..b5780e5 100644
--- a/pint/testsuite/test_quantity.py
+++ b/pint/testsuite/test_quantity.py
@@ -134,7 +134,7 @@ class TestQuantity(QuantityTestCase):
                 r"4.12345678\ \frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}",
             ),
             ("{:P}", "4.12345678 kilogram·meter²/second"),
-            ("{:H}", r"\[4.12345678\ kilogram\ {meter}^{2}/second\]"),
+            ("{:H}", "4.12345678 kilogram meter<sup>2</sup>/second"),
             ("{:C}", "4.12345678 kilogram*meter**2/second"),
             ("{:~}", "4.12345678 kg * m ** 2 / s"),
             (
@@ -142,7 +142,7 @@ class TestQuantity(QuantityTestCase):
                 r"4.12345678\ \frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}",
             ),
             ("{:P~}", "4.12345678 kg·m²/s"),
-            ("{:H~}", r"\[4.12345678\ kg\ {m}^{2}/s\]"),
+            ("{:H~}", "4.12345678 kg m<sup>2</sup>/s"),
             ("{:C~}", "4.12345678 kg*m**2/s"),
             ("{:Lx}", r"\SI[]{4.12345678}{\kilo\gram\meter\squared\per\second}"),
         ):
@@ -176,6 +176,15 @@ class TestQuantity(QuantityTestCase):
             ),
             ("{:.2f~P}", "[0.00 1.00 10000000.00 1000000000000.00 nan inf] kg·m²"),
             ("{:g~P}", "[1e-16 1 1e+07 1e+12 nan inf] kg·m²"),
+            (
+                "{:.2f~H}",
+                (
+                    "<table><tbody><tr><th>Magnitude</th><td style='text-align:left;'>"
+                    "<pre>[0.00 1.00 10000000.00 1000000000000.00 nan inf]</pre></td></tr>"
+                    "<tr><th>Units</th><td style='text-align:left;'>kg m<sup>2</sup></td></tr>"
+                    "</tbody></table>"
+                ),
+            ),
         ):
             with self.subTest(spec):
                 self.assertEqual(spec.format(x), result)
@@ -209,12 +218,12 @@ class TestQuantity(QuantityTestCase):
                 r"4.12345678\ \frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}",
             ),
             ("P", "4.12345678 kilogram·meter²/second"),
-            ("H", r"\[4.12345678\ kilogram\ {meter}^{2}/second\]"),
+            ("H", "4.12345678 kilogram meter<sup>2</sup>/second"),
             ("C", "4.12345678 kilogram*meter**2/second"),
             ("~", "4.12345678 kg * m ** 2 / s"),
             ("L~", r"4.12345678\ \frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}"),
             ("P~", "4.12345678 kg·m²/s"),
-            ("H~", r"\[4.12345678\ kg\ {m}^{2}/s\]"),
+            ("H~", "4.12345678 kg m<sup>2</sup>/s"),
             ("C~", "4.12345678 kg*m**2/s"),
         ):
             with self.subTest(spec):
@@ -224,12 +233,12 @@ class TestQuantity(QuantityTestCase):
     def test_exponent_formatting(self):
         ureg = UnitRegistry()
         x = ureg.Quantity(1e20, "meter")
-        self.assertEqual(f"{x:~H}", r"\[1×10^{20}\ m\]")
+        self.assertEqual(f"{x:~H}", r"1×10<sup>20</sup> m")
         self.assertEqual(f"{x:~L}", r"1\times 10^{20}\ \mathrm{m}")
         self.assertEqual(f"{x:~P}", r"1×10²⁰ m")
 
         x /= 1e40
-        self.assertEqual(f"{x:~H}", r"\[1×10^{-20}\ m\]")
+        self.assertEqual(f"{x:~H}", r"1×10<sup>-20</sup> m")
         self.assertEqual(f"{x:~L}", r"1\times 10^{-20}\ \mathrm{m}")
         self.assertEqual(f"{x:~P}", r"1×10⁻²⁰ m")
 
@@ -250,7 +259,7 @@ class TestQuantity(QuantityTestCase):
 
         ureg = UnitRegistry()
         x = 3.5 * ureg.Unit(UnitsContainer(meter=2, kilogram=1, second=-1))
-        self.assertEqual(x._repr_html_(), r"\[3.5\ kilogram\ {meter}^{2}/second\]")
+        self.assertEqual(x._repr_html_(), "3.5 kilogram meter<sup>2</sup>/second")
         self.assertEqual(
             x._repr_latex_(),
             r"$3.5\ \frac{\mathrm{kilogram} \cdot "
@@ -259,7 +268,7 @@ class TestQuantity(QuantityTestCase):
         x._repr_pretty_(Pretty, False)
         self.assertEqual("".join(alltext), "3.5 kilogram·meter²/second")
         ureg.default_format = "~"
-        self.assertEqual(x._repr_html_(), r"\[3.5\ kg\ {m}^{2}/s\]")
+        self.assertEqual(x._repr_html_(), "3.5 kg m<sup>2</sup>/s")
         self.assertEqual(
             x._repr_latex_(),
             r"$3.5\ \frac{\mathrm{kg} \cdot " r"\mathrm{m}^{2}}{\mathrm{s}}$",
diff --git a/pint/testsuite/test_unit.py b/pint/testsuite/test_unit.py
index 2cce7e0..749a60f 100644
--- a/pint/testsuite/test_unit.py
+++ b/pint/testsuite/test_unit.py
@@ -42,13 +42,13 @@ class TestUnit(QuantityTestCase):
                 r"\frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}",
             ),
             ("{:P}", "kilogram·meter²/second"),
-            ("{:H}", r"\[kilogram\ {meter}^{2}/second\]"),
+            ("{:H}", "kilogram meter<sup>2</sup>/second"),
             ("{:C}", "kilogram*meter**2/second"),
             ("{:Lx}", r"\si[]{\kilo\gram\meter\squared\per\second}"),
             ("{:~}", "kg * m ** 2 / s"),
             ("{:L~}", r"\frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}"),
             ("{:P~}", "kg·m²/s"),
-            ("{:H~}", r"\[kg\ {m}^{2}/s\]"),
+            ("{:H~}", "kg m<sup>2</sup>/s"),
             ("{:C~}", "kg*m**2/s"),
         ):
             with self.subTest(spec):
@@ -63,12 +63,12 @@ class TestUnit(QuantityTestCase):
                 r"\frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}",
             ),
             ("P", "kilogram·meter²/second"),
-            ("H", r"\[kilogram\ {meter}^{2}/second\]"),
+            ("H", "kilogram meter<sup>2</sup>/second"),
             ("C", "kilogram*meter**2/second"),
             ("~", "kg * m ** 2 / s"),
             ("L~", r"\frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}"),
             ("P~", "kg·m²/s"),
-            ("H~", r"\[kg\ {m}^{2}/s\]"),
+            ("H~", "kg m<sup>2</sup>/s"),
             ("C~", "kg*m**2/s"),
         ):
             with self.subTest(spec):
@@ -82,12 +82,12 @@ class TestUnit(QuantityTestCase):
         for spec, result in (
             ("L", r"\mathrm{oil\_barrel}"),
             ("P", "oil_barrel"),
-            ("H", r"\[oil\_barrel\]"),
+            ("H", "oil_barrel"),
             ("C", "oil_barrel"),
             ("~", "oil_bbl"),
             ("L~", r"\mathrm{oil\_bbl}"),
             ("P~", "oil_bbl"),
-            ("H~", r"\[oil\_bbl\]"),
+            ("H~", "oil_bbl"),
             ("C~", "oil_bbl"),
         ):
             with self.subTest(spec):
@@ -104,7 +104,7 @@ class TestUnit(QuantityTestCase):
 
         ureg = UnitRegistry()
         x = ureg.Unit(UnitsContainer(meter=2, kilogram=1, second=-1))
-        self.assertEqual(x._repr_html_(), r"\[kilogram\ {meter}^{2}/second\]")
+        self.assertEqual(x._repr_html_(), "kilogram meter<sup>2</sup>/second")
         self.assertEqual(
             x._repr_latex_(),
             r"$\frac{\mathrm{kilogram} \cdot " r"\mathrm{meter}^{2}}{\mathrm{second}}$",
@@ -112,7 +112,7 @@ class TestUnit(QuantityTestCase):
         x._repr_pretty_(Pretty, False)
         self.assertEqual("".join(alltext), "kilogram·meter²/second")
         ureg.default_format = "~"
-        self.assertEqual(x._repr_html_(), r"\[kg\ {m}^{2}/s\]")
+        self.assertEqual(x._repr_html_(), "kg m<sup>2</sup>/s")
         self.assertEqual(
             x._repr_latex_(), r"$\frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}$"
         )