On the IsDigit () Judgment of negative numbers

Source: Internet
Author: User

-->the start

Today's writing industry suddenly thought, has been using the IsDigit () method to handle the user's input selection is not a number, but if the user entered a negative, will not cause a bug?

Then I tried it and didn't give an error ... Then I was wondering, and I tried it a little bit:

' -10 '. IsDigit () returns false because '-' is not a digit.

Then I want to know how to judge negative numbers, here is the answer from the Internet, recorded here.

1 ' -10 ' 2 if (Num.startswith ('-'andor  num). IsDigit ():3     print(num is an integer)4Else:5     Print (num is not an integer)

Regular Expression method:

1 ' -10 ' 2 Import Re 3 if re.match (r'^-? \.\d+|\d+ (\.\d+)?) ' , num):4     print(num is an integer)5Else: 6     Print (num is not an integer)

A more pythonic approach:

1 ' -10 ' 2 if num.lstrip ('-'). IsDigit ():3     print (num is an integer) 4 Else : 5     Print (num is not an integer)

When I saw the third method, I was very touched and benefited.

<--the End

On the IsDigit () Judgment of negative numbers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.