Python 如何使用 .isdigit 输入负数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28279732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:02:40  来源:igfitidea点击:

How to type negative number with .isdigit?

python

提问by Wdoctor123

when I try this

当我尝试这个时

if question.isdigit() is True:

I can type in numbers fine, and this would filter out alpha/alphanumeric strings

我可以很好地输入数字,这会过滤掉字母/字母数字字符串

when I try 's1' and 's' for example, it would go to (else).

例如,当我尝试 's1' 和 's' 时,它会转到 (else)。

Problem is, when I put negative number such as -1, '.isdigit' counts '-' sign as string value and it rejects it. How can I make it so that '.isdigit' allows negative symbol '-'?

问题是,当我输入负数(例如 -1)时,'.isdigit' 将 '-' 符号计算为字符串值并拒绝它。我怎样才能让'.isdigit'允许负号'-'?

Here is the code. Of the thing i tried.

这是代码。我试过的事情。

while a <=10 + Z:
    question = input("What is " + str(n1) + str(op) + str(n2) + "?")
    a = a+1

    if question.lstrip("-").isdigit() is True:
        ans = ops[op](n1, n2)
        n1 = random.randint(1,9)
        n2 = random.randint(1,9)
        op = random.choice(list(ops))

        if int(question) is ans:
            count = count + 1
            Z = Z + 0
            print ("Well done")
        else:
            count = count + 0
            Z = Z + 0
            print ("WRONG")
    else:
        count = count + 0
        Z = Z + 1
        print ("Please type in the number")

采纳答案by Padraic Cunningham

Use a try/except, if we cannot cast to an int it will set is_digto False:

使用 try/except,如果我们无法转换为 int,它将设置is_digFalse

try:
    int(question)
    is_dig = True
except ValueError:
    is_dig = False
if is_dig:
  ......

Or make a function:

或者做一个函数:

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

if is_digit(question):
   ....

Looking at your edit cast to int at the start,checking if the input is a digit and then casting is pointless, do it in one step:

在开始时查看您的编辑转换为 int,检查输入是否为数字然后转换毫无意义,只需一步即可:

while a < 10: 
     try:
        question = int(input("What is {} {} {} ?".format(n1,op,n2)))
     except ValueError:
        print("Invalid input")
        continue # if we are here we ask user for input again

    ans = ops[op](n1, n2)
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")
    a += 1

Not sure what Z is doing at all but Z = Z + 0is the same as not doing anything to Zat all 1 + 0 == 1

不知道Z的在做,但一切 Z = Z + 0是一样的没有做任何事情来Z在所有1 + 0 == 1

Using a function to take the input we can just use range:

使用函数来获取输入,我们可以只使用范围:

def is_digit(n1,op,n2):
    while True:
        try:
            n = int(input("What is {} {} {} ?".format(n1,op,n2)))
            return n
        except ValueError:
            print("Invalid input")


for _ in range(a):
    question = is_digit(n1,op,n2) # will only return a value when we get legal input
    ans = ops[op](n1, n2)
    n1 = random.randint(1,9)
    n2 = random.randint(1,9)
    op = random.choice(list(ops))

    if question ==  ans:
        print ("Well done")
    else:
        print("Wrong answer")

回答by Maroun

Use lstrip:

使用lstrip

question.lstrip("-").isdigit()

Example:

例子:

>>>'-6'.lstrip('-')
'6'
>>>'-6'.lstrip('-').isdigit()
True

You can lstrip('+-')if you want to consider +6a valid digit.

lstrip('+-')如果你想考虑+6一个有效的数字,你可以。

But I wouldn't use isdigit, you can try int(question), it'll throw an exception if the value cannot be represented as int:

但我不会使用isdigit,你可以尝试int(question),如果值不能表示为,它会抛出异常int

try:
    int(question)
except ValueError:
    # not int

回答by thiruvenkadam

If you do not wish to go for try... except, you could use regular expression

如果您不想尝试……除了,您可以使用正则表达式

if re.match("[+-]?\d", question) is not None:
    question = int(question)
else:
    print "Not a valid number"

With try... except, it is simpler:

使用 try... 除了,它更简单:

try:
    question = int(question)
except ValueError:
    print "Not a valid number"

If isdigit is must and you need to preserve the original value as well, you can either use lstrip as mentioned in an answer given. Another solution will be:

如果 isdigit 是必须的并且您还需要保留原始值,您可以使用给出的答案中提到的 lstrip 。另一个解决方案是:

if question[0]=="-":
    if question[1:].isdigit():
        print "Number"
else:
    if question.isdigit():
        print "Number"