Repository: hgrecco/pint

Issue:
Bad Jupyter rendering of underscores with numpy quantities
default_en.txt makes extensive use of snake_case for all unit names that are made of multiple words.
Such units render poorly in Jupyter Notebook when associated with a numpy magnitude:

![](https://i.postimg.cc/P5JvkPYb/pint-render.png)

Discussion:

Patch:
diff --git a/CHANGES b/CHANGES
index b4694ec..0909b1d 100644
--- a/CHANGES
+++ b/CHANGES
@@ -4,6 +4,8 @@ Pint Changelog
 0.10 (unreleased)
 -----------------
 
+- Fix HTML (Jupyter Notebook) and LateX representation of some units
+  (Issue #927, Thanks Guido Imperiale)
 - **BREAKING CHANGE**:
   Implement NEP-18 <https://numpy.org/neps/nep-0018-array-function-protocol.html> for
   Pint Quantities. Most NumPy functions that previously stripped units when applied to
diff --git a/pint/formatting.py b/pint/formatting.py
index cd23de8..dc92d86 100644
--- a/pint/formatting.py
+++ b/pint/formatting.py
@@ -75,7 +75,7 @@ _FORMATS = {
         'single_denominator': True,
         'product_fmt': r' ',
         'division_fmt': r'{}/{}',
-        'power_fmt': '{}<sup>{}</sup>',
+        'power_fmt': '{}^{}',
         'parentheses_fmt': r'({})',
         },
 
@@ -215,13 +215,19 @@ def format_unit(unit, spec, **kwspec):
     fmt.update(kwspec)
 
     if spec == 'L':
-        rm = [(r'\mathrm{{{}}}'.format(u), p) for u, p in unit.items()]
-        result = formatter(rm, **fmt)
+        # Latex
+        rm = [
+            (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:
-        result = formatter(unit.items(), **fmt)
-    if spec == 'L':
-        result = result.replace('[', '{').replace(']', '}')
-    return result
+        # Plain text
+        return formatter(unit.items(), **fmt)
 
 
 def siunitx_format_unit(units):


Test patch:
diff --git a/pint/testsuite/test_measurement.py b/pint/testsuite/test_measurement.py
index 47edc5c..931be49 100644
--- a/pint/testsuite/test_measurement.py
+++ b/pint/testsuite/test_measurement.py
@@ -42,61 +42,83 @@ class TestMeasurement(QuantityTestCase):
     def test_format(self):
         v, u = self.Q_(4.0, 's ** 2'), self.Q_(.1, 's ** 2')
         m = self.ureg.Measurement(v, u)
-        self.assertEqual(str(m), '(4.00 +/- 0.10) second ** 2')
-        self.assertEqual(repr(m), '<Measurement(4.00, 0.10, second ** 2)>')
-        #self.assertEqual('{:!s}'.format(m), '(4.00 +/- 0.10) second ** 2')
-        #self.assertEqual('{:!r}'.format(m), '<Measurement(4.0-, 0.10, second ** 2)>')
-        self.assertEqual('{0:P}'.format(m), '(4.00 ± 0.10) second²')
-        self.assertEqual('{0:L}'.format(m), r'\left(4.00 \pm 0.10\right)\ \mathrm{second}^{2}')
-        self.assertEqual('{0:H}'.format(m), '(4.00 &plusmn; 0.10) second<sup>2</sup>')
-        self.assertEqual('{0:C}'.format(m), '(4.00+/-0.10) second**2')
-        self.assertEqual('{0:Lx}'.format(m), r'\SI[separate-uncertainty=true]{4.00(10)}{\second\squared}')
-        self.assertEqual('{0:.1f}'.format(m), '(4.0 +/- 0.1) second ** 2')
-        self.assertEqual('{0:.1fP}'.format(m), '(4.0 ± 0.1) second²')
-        self.assertEqual('{0:.1fL}'.format(m), r'\left(4.0 \pm 0.1\right)\ \mathrm{second}^{2}')
-        self.assertEqual('{0:.1fH}'.format(m), '(4.0 &plusmn; 0.1) second<sup>2</sup>')
-        self.assertEqual('{0:.1fC}'.format(m), '(4.0+/-0.1) second**2')
-        self.assertEqual('{0:.1fLx}'.format(m), r'\SI[separate-uncertainty=true]{4.0(1)}{\second\squared}')
+
+        for spec, result in (
+            ("{}", '(4.00 +/- 0.10) second ** 2'),
+            ("{!r}", '<Measurement(4.00, 0.10, second ** 2)>'),
+            ('{:P}', '(4.00 ± 0.10) second²'),
+            ('{:L}', r'\left(4.00 \pm 0.10\right)\ \mathrm{second}^{2}'),
+            ('{:H}', '(4.00 &plusmn; 0.10) second^2'),
+            ('{:C}', '(4.00+/-0.10) second**2'),
+            ('{:Lx}', r'\SI[separate-uncertainty=true]{4.00(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}', '(4.0 &plusmn; 0.1) second^2'),
+            ('{:.1fC}', '(4.0+/-0.1) second**2'),
+            ('{:.1fLx}', r'\SI[separate-uncertainty=true]{4.0(1)}{\second\squared}'),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(m), result)
 
     def test_format_paru(self):
         v, u = self.Q_(0.20, 's ** 2'), self.Q_(0.01, 's ** 2')
         m = self.ureg.Measurement(v, u)
-        self.assertEqual('{0:uS}'.format(m), '0.200(10) second ** 2')
-        self.assertEqual('{0:.3uS}'.format(m), '0.2000(100) second ** 2')
-        self.assertEqual('{0:.3uSP}'.format(m), '0.2000(100) second²')
-        self.assertEqual('{0:.3uSL}'.format(m), r'0.2000\left(100\right)\ \mathrm{second}^{2}')
-        self.assertEqual('{0:.3uSH}'.format(m), '0.2000(100) second<sup>2</sup>')
-        self.assertEqual('{0:.3uSC}'.format(m), '0.2000(100) second**2')
+
+        for spec, result in (
+            ('{:uS}', '0.200(10) second ** 2'),
+            ('{:.3uS}', '0.2000(100) second ** 2'),
+            ('{:.3uSP}', '0.2000(100) second²'),
+            ('{:.3uSL}', r'0.2000\left(100\right)\ \mathrm{second}^{2}'),
+            ('{:.3uSH}', '0.2000(100) second^2'),
+            ('{:.3uSC}', '0.2000(100) second**2'),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(m), result)
 
     def test_format_u(self):
         v, u = self.Q_(0.20, 's ** 2'), self.Q_(0.01, 's ** 2')
         m = self.ureg.Measurement(v, u)
-        self.assertEqual('{0:.3u}'.format(m), '(0.2000 +/- 0.0100) second ** 2')
-        self.assertEqual('{0:.3uP}'.format(m), '(0.2000 ± 0.0100) second²')
-        self.assertEqual('{0:.3uL}'.format(m), r'\left(0.2000 \pm 0.0100\right)\ \mathrm{second}^{2}')
-        self.assertEqual('{0:.3uH}'.format(m), '(0.2000 &plusmn; 0.0100) second<sup>2</sup>')
-        self.assertEqual('{0:.3uC}'.format(m), '(0.2000+/-0.0100) second**2')
-        self.assertEqual('{0:.3uLx}'.format(m), r'\SI[separate-uncertainty=true]{0.2000(100)}{\second\squared}')
-        self.assertEqual('{0:.1uLx}'.format(m), r'\SI[separate-uncertainty=true]{0.20(1)}{\second\squared}')
+
+        for spec, result in (
+            ('{:.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}', '(0.2000 &plusmn; 0.0100) second^2'),
+            ('{:.3uC}', '(0.2000+/-0.0100) second**2'),
+            ('{:.3uLx}', r'\SI[separate-uncertainty=true]{0.2000(100)}{\second\squared}'),
+            ('{:.1uLx}', r'\SI[separate-uncertainty=true]{0.20(1)}{\second\squared}'),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(m), result)
 
     def test_format_percu(self):
         self.test_format_perce()
         v, u = self.Q_(0.20, 's ** 2'), self.Q_(0.01, 's ** 2')
         m = self.ureg.Measurement(v, u)
-        self.assertEqual('{0:.1u%}'.format(m), '(20 +/- 1)% second ** 2')
-        self.assertEqual('{0:.1u%P}'.format(m), '(20 ± 1)% second²')
-        self.assertEqual('{0:.1u%L}'.format(m), r'\left(20 \pm 1\right) \%\ \mathrm{second}^{2}')
-        self.assertEqual('{0:.1u%H}'.format(m), '(20 &plusmn; 1)% second<sup>2</sup>')
-        self.assertEqual('{0:.1u%C}'.format(m), '(20+/-1)% second**2')
+
+        for spec, result in (
+            ('{:.1u%}', '(20 +/- 1)% second ** 2'),
+            ('{:.1u%P}', '(20 ± 1)% second²'),
+            ('{:.1u%L}', r'\left(20 \pm 1\right) \%\ \mathrm{second}^{2}'),
+            ('{:.1u%H}', '(20 &plusmn; 1)% second^2'),
+            ('{:.1u%C}', '(20+/-1)% second**2'),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(m), result)
 
     def test_format_perce(self):
         v, u = self.Q_(0.20, 's ** 2'), self.Q_(0.01, 's ** 2')
         m = self.ureg.Measurement(v, u)
-        self.assertEqual('{0:.1ue}'.format(m), '(2.0 +/- 0.1)e-01 second ** 2')
-        self.assertEqual('{0:.1ueP}'.format(m), '(2.0 ± 0.1)×10⁻¹ second²')
-        self.assertEqual('{0:.1ueL}'.format(m), r'\left(2.0 \pm 0.1\right) \times 10^{-1}\ \mathrm{second}^{2}')
-        self.assertEqual('{0:.1ueH}'.format(m), '(2.0 &plusmn; 0.1)e-01 second<sup>2</sup>')
-        self.assertEqual('{0:.1ueC}'.format(m), '(2.0+/-0.1)e-01 second**2')
+        for spec, result in (
+            ('{:.1ue}', '(2.0 +/- 0.1)e-01 second ** 2'),
+            ('{:.1ueP}', '(2.0 ± 0.1)×10⁻¹ second²'),
+            ('{:.1ueL}', r'\left(2.0 \pm 0.1\right) \times 10^{-1}\ \mathrm{second}^{2}'),
+            ('{:.1ueH}', '(2.0 &plusmn; 0.1)e-01 second^2'),
+            ('{:.1ueC}', '(2.0+/-0.1)e-01 second**2'),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(m), result)
 
     def test_raise_build(self):
         v, u = self.Q_(1.0, 's'), self.Q_(.1, 's')
diff --git a/pint/testsuite/test_quantity.py b/pint/testsuite/test_quantity.py
index dc82ff2..71c9e35 100644
--- a/pint/testsuite/test_quantity.py
+++ b/pint/testsuite/test_quantity.py
@@ -107,23 +107,31 @@ class TestQuantity(QuantityTestCase):
 
     def test_quantity_format(self):
         x = self.Q_(4.12345678, UnitsContainer(meter=2, kilogram=1, second=-1))
-        for spec, result in (('{0}', str(x)), ('{0!s}', str(x)), ('{0!r}', repr(x)),
-                             ('{0.magnitude}',  str(x.magnitude)), ('{0.units}',  str(x.units)),
-                             ('{0.magnitude!s}',  str(x.magnitude)), ('{0.units!s}',  str(x.units)),
-                             ('{0.magnitude!r}',  repr(x.magnitude)), ('{0.units!r}',  repr(x.units)),
-                             ('{0:.4f}', '{0:.4f} {1!s}'.format(x.magnitude, x.units)),
-                             ('{0:L}', r'4.12345678\ \frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
-                             ('{0:P}', '4.12345678 kilogram·meter²/second'),
-                             ('{0:H}', '4.12345678 kilogram meter<sup>2</sup>/second'),
-                             ('{0:C}', '4.12345678 kilogram*meter**2/second'),
-                             ('{0:~}', '4.12345678 kg * m ** 2 / s'),
-                             ('{0:L~}', r'4.12345678\ \frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}'),
-                             ('{0:P~}', '4.12345678 kg·m²/s'),
-                             ('{0:H~}', '4.12345678 kg m<sup>2</sup>/s'),
-                             ('{0:C~}', '4.12345678 kg*m**2/s'),
-                             ('{0:Lx}', r'\SI[]{4.12345678}{\kilo\gram\meter\squared\per\second}'),
-                             ):
-            self.assertEqual(spec.format(x), result)
+        for spec, result in (
+            ('{}', str(x)),
+            ('{!s}', str(x)),
+            ('{!r}', repr(x)),
+            ('{.magnitude}',  str(x.magnitude)),
+            ('{.units}',  str(x.units)),
+            ('{.magnitude!s}',  str(x.magnitude)),
+            ('{.units!s}',  str(x.units)),
+            ('{.magnitude!r}',  repr(x.magnitude)),
+            ('{.units!r}',  repr(x.units)),
+            ('{:.4f}', f'{x.magnitude:.4f} {x.units!s}'),
+            ('{:L}', r'4.12345678\ \frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
+            ('{:P}', '4.12345678 kilogram·meter²/second'),
+            ('{:H}', '4.12345678 kilogram meter^2/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~}', '4.12345678 kg m^2/s'),
+            ('{:C~}', '4.12345678 kg*m**2/s'),
+            ('{:Lx}', r'\SI[]{4.12345678}{\kilo\gram\meter\squared\per\second}'),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(x), result)
+
         # Check the special case that prevents e.g. '3 1 / second'
         x = self.Q_(3, UnitsContainer(second=-1))
         self.assertEqual('{0}'.format(x), '3 / second')
@@ -131,15 +139,17 @@ class TestQuantity(QuantityTestCase):
     @helpers.requires_numpy()
     def test_quantity_array_format(self):
         x = self.Q_(np.array([1e-16, 1.0000001, 10000000.0, 1e12, np.nan, np.inf]), "kg * m ** 2")
-        for spec, result in (('{0}',  str(x)),
-                             ('{0.magnitude}', str(x.magnitude)),
-                             ('{0:e}', "[1.000000e-16 1.000000e+00 1.000000e+07 1.000000e+12 nan inf] kilogram * meter ** 2"),
-                             ('{0:E}', "[1.000000E-16 1.000000E+00 1.000000E+07 1.000000E+12 NAN INF] kilogram * meter ** 2"),
-                             ('{0:.2f}', "[0.00 1.00 10000000.00 1000000000000.00 nan inf] kilogram * meter ** 2"),
-                             ('{0:.2f~P}', "[0.00 1.00 10000000.00 1000000000000.00 nan inf] kg·m²"),
-                             ('{0:g~P}', "[1e-16 1 1e+07 1e+12 nan inf] kg·m²"),
-                             ):
-            self.assertEqual(spec.format(x), result)
+        for spec, result in (
+            ('{}',  str(x)),
+            ('{.magnitude}', str(x.magnitude)),
+            ('{:e}', "[1.000000e-16 1.000000e+00 1.000000e+07 1.000000e+12 nan inf] kilogram * meter ** 2"),
+            ('{:E}', "[1.000000E-16 1.000000E+00 1.000000E+07 1.000000E+12 NAN INF] kilogram * meter ** 2"),
+            ('{:.2f}', "[0.00 1.00 10000000.00 1000000000000.00 nan inf] kilogram * meter ** 2"),
+            ('{:.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²"),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(x), result)
 
     def test_format_compact(self):
         q1 = (200e-9 * self.ureg.s).to_compact()
@@ -161,22 +171,23 @@ class TestQuantity(QuantityTestCase):
         self.assertEqual('{0:#.1f}'.format(q2), '{0}'.format(q2b))
         self.assertEqual('{0:#.1f}'.format(q3), '{0}'.format(q3b))
 
-
     def test_default_formatting(self):
         ureg = UnitRegistry()
         x = ureg.Quantity(4.12345678, UnitsContainer(meter=2, kilogram=1, second=-1))
-        for spec, result in (('L', r'4.12345678\ \frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
-                             ('P', '4.12345678 kilogram·meter²/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~', '4.12345678 kg m<sup>2</sup>/s'),
-                             ('C~', '4.12345678 kg*m**2/s'),
-                             ):
-            ureg.default_format = spec
-            self.assertEqual('{0}'.format(x), result)
+        for spec, result in (
+            ('L', r'4.12345678\ \frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
+            ('P', '4.12345678 kilogram·meter²/second'),
+            ('H', '4.12345678 kilogram meter^2/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~', '4.12345678 kg m^2/s'),
+            ('C~', '4.12345678 kg*m**2/s'),
+        ):
+            with self.subTest(spec):
+                ureg.default_format = spec
+                self.assertEqual(f'{x}', result)
 
     def test_exponent_formatting(self):
         ureg = UnitRegistry()
@@ -205,14 +216,14 @@ class TestQuantity(QuantityTestCase):
         ureg = UnitRegistry()
         x = 3.5 * ureg.Unit(UnitsContainer(meter=2, kilogram=1, second=-1))
         self.assertEqual(x._repr_html_(),
-                         "3.5 kilogram meter<sup>2</sup>/second")
+                         "3.5 kilogram meter^2/second")
         self.assertEqual(x._repr_latex_(),
                          r'$3.5\ \frac{\mathrm{kilogram} \cdot '
                          r'\mathrm{meter}^{2}}{\mathrm{second}}$')
         x._repr_pretty_(Pretty, False)
         self.assertEqual("".join(alltext), "3.5 kilogram·meter²/second")
         ureg.default_format = "~"
-        self.assertEqual(x._repr_html_(), "3.5 kg m<sup>2</sup>/s")
+        self.assertEqual(x._repr_html_(), "3.5 kg m^2/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 1932117..30ccec0 100644
--- a/pint/testsuite/test_unit.py
+++ b/pint/testsuite/test_unit.py
@@ -33,37 +33,60 @@ class TestUnit(QuantityTestCase):
 
     def test_unit_formatting(self):
         x = self.U_(UnitsContainer(meter=2, kilogram=1, second=-1))
-        for spec, result in (('{0}', str(x)), ('{0!s}', str(x)),
-                             ('{0!r}', repr(x)),
-                             ('{0:L}', r'\frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
-                             ('{0:P}', 'kilogram·meter²/second'),
-                             ('{0:H}', 'kilogram meter<sup>2</sup>/second'),
-                             ('{0:C}', 'kilogram*meter**2/second'),
-                             ('{0:Lx}', r'\si[]{\kilo\gram\meter\squared\per\second}'),
-                             ('{0:~}', 'kg * m ** 2 / s'),
-                             ('{0:L~}', r'\frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}'),
-                             ('{0:P~}', 'kg·m²/s'),
-                             ('{0:H~}', 'kg m<sup>2</sup>/s'),
-                             ('{0:C~}', 'kg*m**2/s'),
-                             ):
-            self.assertEqual(spec.format(x), result)
+        for spec, result in (
+            ('{}', str(x)),
+            ('{!s}', str(x)),
+            ('{!r}', repr(x)),
+            ('{:L}', r'\frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
+            ('{:P}', 'kilogram·meter²/second'),
+            ('{:H}', 'kilogram meter^2/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~}', 'kg m^2/s'),
+            ('{:C~}', 'kg*m**2/s'),
+        ):
+            with self.subTest(spec):
+                self.assertEqual(spec.format(x), result)
 
     def test_unit_default_formatting(self):
         ureg = UnitRegistry()
         x = ureg.Unit(UnitsContainer(meter=2, kilogram=1, second=-1))
-        for spec, result in (('L', r'\frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
-                             ('P', 'kilogram·meter²/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~', 'kg m<sup>2</sup>/s'),
-                             ('C~', 'kg*m**2/s'),
-                             ):
-            ureg.default_format = spec
-            self.assertEqual('{0}'.format(x), result,
-                             'Failed for {0}, {1}'.format(spec, result))
+        for spec, result in (
+            ('L', r'\frac{\mathrm{kilogram} \cdot \mathrm{meter}^{2}}{\mathrm{second}}'),
+            ('P', 'kilogram·meter²/second'),
+            ('H', 'kilogram meter^2/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~', 'kg m^2/s'),
+            ('C~', 'kg*m**2/s'),
+        ):
+            with self.subTest(spec):
+                ureg.default_format = spec
+                self.assertEqual(f'{x}', result, f'Failed for {spec}, {result}')
+
+    def test_unit_formatting_snake_case(self):
+        # Test that snake_case units are escaped where appropriate
+        ureg = UnitRegistry()
+        x = ureg.Unit(UnitsContainer(oil_barrel=1))
+        for spec, result in (
+            ('L', r'\mathrm{oil\_barrel}'),
+            ('P', 'oil_barrel'),
+            ('H', 'oil\_barrel'),
+            ('C', 'oil_barrel'),
+            ('~', 'oil_bbl'),
+            ('L~', r'\mathrm{oil\_bbl}'),
+            ('P~', 'oil_bbl'),
+            ('H~', 'oil\_bbl'),
+            ('C~', 'oil_bbl'),
+        ):
+            with self.subTest(spec):
+                ureg.default_format = spec
+                self.assertEqual(f'{x}', result, f'Failed for {spec}, {result}')
 
     def test_ipython(self):
         alltext = []
@@ -75,13 +98,13 @@ class TestUnit(QuantityTestCase):
 
         ureg = UnitRegistry()
         x = ureg.Unit(UnitsContainer(meter=2, kilogram=1, second=-1))
-        self.assertEqual(x._repr_html_(), "kilogram meter<sup>2</sup>/second")
+        self.assertEqual(x._repr_html_(), "kilogram meter^2/second")
         self.assertEqual(x._repr_latex_(), r'$\frac{\mathrm{kilogram} \cdot '
                                            r'\mathrm{meter}^{2}}{\mathrm{second}}$')
         x._repr_pretty_(Pretty, False)
         self.assertEqual("".join(alltext), "kilogram·meter²/second")
         ureg.default_format = "~"
-        self.assertEqual(x._repr_html_(), "kg m<sup>2</sup>/s")
+        self.assertEqual(x._repr_html_(), "kg m^2/s")
         self.assertEqual(x._repr_latex_(),
                          r'$\frac{\mathrm{kg} \cdot \mathrm{m}^{2}}{\mathrm{s}}$')
         alltext = []