试图检测有条件的数字

时间:2017-07-30 09:19:24

标签: python string console numbers

我有一个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

基本上我想要的是能够输入:'1st 10,2nd 20'的原始输入,然后将这些数字打印到控制台。有没有办法做到这一点?

2 个答案:

答案 0 :(得分: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. 检查输入字符串是否包含第1和第2个
  2. 检查输入字符串是否具有正确的长度
  3. 检查输入字符串的各个令牌是否正确 一个。首先检查它们的长度是否正确 湾检查它们的顺序是否正确
  4. 检查我们想要提取的最终元素实际上是一个数字。
  5. 在这里测试:https://repl.it/Jooi/8

答案 1 :(得分: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