How to type negative number with .isdigit?

前端 未结 4 1398
无人及你
无人及你 2020-12-09 09:58

when I try this

if question.isdigit() is True:

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

whe

4条回答
  •  粉色の甜心
    2020-12-09 10:00

    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:
        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:

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

提交回复
热议问题