How to type negative number with .isdigit?

前端 未结 4 1401
无人及你
无人及你 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:14

    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
    

提交回复
热议问题