2017-07-30 26 views
1

我有一個if語句檢查語句中的任何整數的變量,但我無法使其工作。這是我到目前爲止有:試圖檢測條件中的數字

import re 
c = input('input your numbers: ') 
if(c == '1st ' + %d + ', 2nd ' + %d): 
    n = re.findall('\d+', c) 
    for i in n[:1]: 
     print (i) ##this prints the 1st number entered 
    print (n[-1]) ##this prints the second number entered 

基本上我想要的是能夠在一個原始輸入輸入:「10月1日,2日20」,然後讓打印到控制檯這些數字。有沒有辦法做到這一點?

+3

你的意思是這個'如果(C == '1' +%d + '第二' +% d):? –

+0

當你運行你的代碼時,你看到了什麼錯誤? – quamrana

回答

0

你可以按照這個過程:

import re 
c = input('input your numbers: ') 
if('1st' not in c or '2nd' not in c): 
    n = re.findall('\d+', c) 
    for i in n[:1]: 
     print (i) ##this prints the 1st number entered 
    print (n[-1]) ##this prints the second number entered 
+0

嗯,倒置條件? 'if(c中的'1st'和c中的'2nd':'? – quamrana

+0

我不確定這會回答原來的問題。在他的條件下,他正在尋找輸入字符串的特定結構。這裏的條件只是檢查輸入部分是否正確。 – Tr1gZer0

0

不完全相信我會這樣實現它,但我只是建立關你已經擁有:

import re 

def is_number(n): 
    try: 
    int(n) 
    except ValueError: 
    return False 
    return True 

def validate_token(token, prefix): 
    tokens = token.split() 
    if len(tokens) != 2: 
    print ('{} does not contain a second entry'.format(token)) 
    return False 
    if tokens[0] != prefix: 
    print ('Entry is not in correct position: {0}. Was expecting {1}.'.format(token, prefix)) 
    return False 
    return True 

def read_input(): 
    first = '1st' 
    second = '2nd' 
    c = input('input your numbers: ') 
    if (not (first in c and second in c)): 
    print ('Please enter in format: 1st n1, 2nd n2') 
    return 

    tokens = c.split(',') 
    if len(tokens) != 2: 
    print ('Please separate entries 1st and 2nd by a ","') 
    return 

    if (not validate_token(tokens[0], first) or not validate_token(tokens[1], second)): 
    print ('Not a valid entry invalid...') 
    return 

    n1 = tokens[0].split()[1] 
    n2 = tokens[1].split()[1] 

    if (not is_number(n1)): 
    print('n1 is not a number!') 
    return 

    if (not is_number(n2)): 
    print('n2 is not a number!') 
    return 

    n = re.findall(r'\d+', c) 
    for i in n[:1]: 
    print (i) ##this prints the 1st number entered 
    print (n[-1]) ##this prints the second number entered 

read_input() 

是單斜槓作品。道歉。更新鏈接及以上的代碼。請注意,上面的大部分工作正在驗證正確的輸入。如果有人有更簡潔的東西,請分享。

讓我們在這裏解釋做了驗證:

  1. 檢查輸入字符串包含第一和第二
  2. 檢查輸入字符串有正確的長度
  3. 檢查輸入字符串的個人令牌是正確的 a。首先檢查它們的長度是否正確 b。檢查它們的排列順序是否正確
  4. 檢查我們希望提取的最後一個元素實際上是一個數字。

這裏測試:https://repl.it/Jooi/8

+0

你用單斜槓試過了嗎? – ksai

+0

'\ d'是一個數字(0-9範圍內的一個字符),'+'表示1次或更多次。所以,'\ d +'是1個或多個數字。所以,'\ d +'效果很好。 :) –

+0

@ksai更新代碼謝謝。我確實用一個斜線試了一下,我相信我原來的bug是在其他地方。 – Tr1gZer0