簡體   English   中英

如何解析輸入的字符串以提取單個數字

[英]How to parse an inputted string to extract individual numbers

一旦我弄清楚了,就會感到愚蠢。

我正在編寫的程序會提示您進行操作(例如9 + 3),然后打印結果。

舉例來看:

>>>Enter an operation: 9+3
>>>Result: 12

我將為運算符+,-,*和/提供四個單獨的函數,以及另一個函數,以接收用戶輸入並在適當的函數返回后打印結果。

到目前為止,這是我的代碼(我僅包含一個運算符):

def add(n, y):
    result = ""
    result = n + y
    return result

def main():
    op = input("Enter an operation: ")
    for i in range(1,len(op)):
        n = n[0]
        y = y[2]
        if (i == "+"):
            result = add(n, y)
    print("Result: ", result)
    print("Bye")

我在外殼狀態n和y中的錯誤未分配,因此無法從輸入中正確解析它們。

因為它們沒有在函數主體中分配,並且在全局范圍中不可用:

def main():
    op = input("Enter an operation: ")
    for i in range(1,len(op)):
        n = n[0]  # no n here yet so n[0] won't work
        y = y[2]  # no y here yet so y[2] won't work

我認為您的目的是解析輸入,然后使用這些值執行加法運算,如下所示:

def main():
    op = input("Enter an operation: ")
    i = op[1]
    n = int(op[0])
    y = int(op[2])

    if i == "+":
        result = add(n, y)
    print("Result: ", result)
    print("Bye")

但這僅適用於一個數字參數,因此您可能會考慮使用正則表達式進行一些適當的解析,但這是另一個問題。

您的代碼有問題:

main ,在n = n[0] ,您沒有定義n 所以你會得到一個錯誤。 對於y = y[2] add要添加字符串。 因此您將得到'93'作為答案。

為了進行正確的解析,請使用regex
或者,如果您想快速工作,請使用較少的編碼版本(如果正在學習,則不建議使用)
嘗試這個:

def main():
    while True:
        # just a variable used to check for errors.
        not_ok = False

        inp = input("Enter an operation: ")
        inp = inp.replace('\t',' ')

        for char in inp:
            if char not in '\n1234567890/\\+-*().': # for eval, check if the 
                print 'invalid input'
                not_ok = True # there is a problem
                break
        if not_ok: # the problem is caught
            continue # Go back to start

        # the eval
        try:
            print 'Result: {}'.format(eval(inp)) # prints output for correct input.
        except Exception:
            print 'invalid input'
        else:
            break # end loop

一些正則表達式鏈接: 1 2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM