Python - 如何将零添加到 -1 和 1 之间的浮点数

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

所以我正在制作一个 ,但它不理解以点开头的数字。这意味着解析器可以理解 "0.5",但不能理解 ".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)

所以,我的objective是将每个没有整数部分的小数替换为"0.",然后是小数(例如,将".5"替换为"0.5""-.2""-0.2"".0""0.0" 等...),以便解析器可以理解。所以,我想出了这个代码:

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"

这段代码有效,但这是最好的方法吗?

没有。如果您的语言允许 .5-.7 形式的数字文字,那么您的解析器应该更改为接受此类文字。

expression = "-.0"
expression = float(expression)
expression = str(expression)
print(expression)

您是否考虑过在您的解析器中包含一些 regex?你可以做适当的检查,例如通过

import re
dec_sep = '.'
dec_pattern = '[+-]?[0-9]+['+dec_sep+'][0-9]*|[+-]?[0-9]*['+dec_sep+'][0-9]+'

for s in ['.7', '-.4', '4.', '+3.']:
    print(re.fullmatch(dec_pattern, s))

并得到

<re.Match object; span=(0, 2), match='.7'>
<re.Match object; span=(0, 3), match='-.4'>
<re.Match object; span=(0, 2), match='4.'>
<re.Match object; span=(0, 3), match='+3.'>