Search code examples
pythonpython-3.xparsingpyparsing

Python - How to add zeros to floating point numbers between -1 and 1


So I am making a parser, but it is doesn't understand numbers that starts with a point. This means that "0.5" is understood by the parser, but not ".5":

>>> evaluate("0.5")
0.5

>>> evaluate(".5")
SyntaxError: Expected {{[- | +] {{{{{{{W:(ABCD...,ABCD...) Suppress:("(") Forward: ...} Suppress:(")")} | 'PI'} | 'E'} | 'PHI'} | 'TAU'} | Combine:({{W:(+-01...,0123...) [{"." [W:(0123...)]}]} [{'E' W:(+-01...,0123...)}]})}} | {[- | +] Group:({{Suppress:("(") Forward: ...} Suppress:(")")})}} (at char 0), (line:1, col:1)

So, my objective is to replace every decimal number without an integer part by "0." followed by the decimals (for instance, replace ".5" by "0.5", "-.2" by "-0.2", ".0" by "0.0", etc...), so that it can be understood by the parser. So, I came up with this code:

expression = "-.2"
expression = list(expression)

for key, char in enumerate(expression):
    # If first character in the string is a point, add "0" before it if there is a digit after the point
    if not key:
        if char == ".":
            try:
                if expression[key+1].isdigit():
                    expression.insert(key, "0")
            except: pass
        continue

    # If a point is not the first character in the string, add "0" before it if there are no digits before the point but one after the point
    if char == "." and not expression[key-1].isdigit():
        try:
            if expression[key+1].isdigit():
                expression.insert(key, "0")
        except: continue

expression = "".join(expression)
print(expression)   # Result is "-0.2"

This code works, but is it the best way to do it?


Solution

  • No. If your language allows numeric literals of the form .5 or -.7 then your parser should be changed to accept such literals.