Skip to content

Commit 12b43e0

Browse files
refactor: extract _SUPERSCRIPT_MAP constant and simplify scientific()
1 parent 877e1fd commit 12b43e0

1 file changed

Lines changed: 15 additions & 20 deletions

File tree

src/humanize/number.py

Lines changed: 15 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,20 @@
99
from .i18n import _ngettext_noop as NS_
1010
from .i18n import _pgettext as P_
1111

12+
_SUPERSCRIPT_MAP = {
13+
"0": "⁰",
14+
"1": "¹",
15+
"2": "²",
16+
"3": "³",
17+
"4": "⁴",
18+
"5": "⁵",
19+
"6": "⁶",
20+
"7": "⁷",
21+
"8": "⁸",
22+
"9": "⁹",
23+
"-": "⁻",
24+
}
25+
1226
TYPE_CHECKING = False
1327
if TYPE_CHECKING:
1428
from typing import TypeAlias
@@ -415,19 +429,6 @@ def scientific(value: NumberOrString, precision: int = 2) -> str:
415429
"""
416430
import math
417431

418-
exponents = {
419-
"0": "⁰",
420-
"1": "¹",
421-
"2": "²",
422-
"3": "³",
423-
"4": "⁴",
424-
"5": "⁵",
425-
"6": "⁶",
426-
"7": "⁷",
427-
"8": "⁸",
428-
"9": "⁹",
429-
"-": "⁻",
430-
}
431432
try:
432433
value = float(value)
433434
if not math.isfinite(value):
@@ -442,13 +443,7 @@ def scientific(value: NumberOrString, precision: int = 2) -> str:
442443

443444
part2 = re.sub(r"^\+?(\-?)0*(.+)$", r"\1\2", part2)
444445

445-
new_part2 = []
446-
for char in part2:
447-
new_part2.append(exponents[char])
448-
449-
final_str = part1 + " x 10" + "".join(new_part2)
450-
451-
return final_str
446+
return part1 + " x 10" + "".join(_SUPERSCRIPT_MAP[char] for char in part2)
452447

453448

454449
def clamp(

0 commit comments

Comments
 (0)