Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

python - How to type negative number with .isdigit?

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).

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 '-'?

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use lstrip:

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

Example:

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

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...