Python Forum
replacement for fpformat.extract
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replacement for fpformat.extract
#2
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 »
Reply


Messages In This Thread
replacement for fpformat.extract - by GbSig1998 - Apr-12-2024, 01:41 PM
RE: replacement for fpformat.extract - by Gribouillis - Apr-12-2024, 02:42 PM
RE: replacement for fpformat.extract - by GbSig1998 - Apr-12-2024, 04:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  If I need to do regex replacement 27000 times, how to shorten it? tatahuft 4 947 Dec-26-2024, 01:51 AM
Last Post: deanhystad
  String replacement in DB WJSwan 0 1,282 Dec-28-2022, 05:31 AM
Last Post: WJSwan
Exclamation IndexError: Replacement index 2 out of range for positional args tuple - help? MrKnd94 2 14,285 Oct-14-2022, 09:57 PM
Last Post: MrKnd94
  Extract the largest value from a group without replacement (beginner) preliator 1 2,718 Aug-12-2020, 01:56 PM
Last Post: DPaul
  Simple automated SoapAPI Call with single variable replacement from csv asaxty 1 2,884 Jun-30-2020, 06:38 PM
Last Post: asaxty
  line replacement help mdalireza 8 5,027 Nov-11-2019, 12:54 PM
Last Post: mdalireza
  xml replacement with python josesalazmit 3 9,910 Feb-24-2019, 07:28 PM
Last Post: stullis
  Best replacement for pyzmail in lines 15 and 16 Pedroski55 0 3,173 Nov-03-2018, 06:12 AM
Last Post: Pedroski55
  Is pathlib a viable replacement for os.path? j.crater 4 11,872 Jan-13-2018, 09:49 AM
Last Post: Gribouillis
  Using python for text replacement omar 1 4,590 Dec-22-2016, 01:36 AM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020