Apr-12-2024, 02:42 PM
(This post was last modified: Apr-12-2024, 02:42 PM by Gribouillis.)
Here is the Python 2 code of fpformat.extract(), you could perhaps convert this function directly, or it may run out of the box in Python 3.
# Compiled regular expression to "decode" a number decoder = re.compile(r'^([-+]?)(\d*)((?:\.\d*)?)(([eE][-+]?\d+)?)$') # \0 the whole thing # \1 leading sign or empty # \2 digits left of decimal point # \3 fraction (empty or begins with point) # \4 exponent part (empty or begins with 'e' or 'E') try: class NotANumber(ValueError): pass except TypeError: NotANumber = 'fpformat.NotANumber' def extract(s): """Return (sign, intpart, fraction, expo) or raise an exception: sign is '+' or '-' intpart is 0 or more digits beginning with a nonzero fraction is 0 or more digits expo is an integer""" res = decoder.match(s) if res is None: raise NotANumber, s sign, intpart, fraction, exppart = res.group(1,2,3,4) intpart = intpart.lstrip('0'); if sign == '+': sign = '' if fraction: fraction = fraction[1:] if exppart: expo = int(exppart[1:]) else: expo = 0 return sign, intpart, fraction, expo
« We can solve any problem by introducing an extra level of indirection »