Python determines whether a string is a pure numeric code

Source: Internet
Author: User

Judged by the code below, through the anomaly can not distinguish between the positive and negative signs, regular expressions can be more flexible according to their needs to write, through the IsDigit method to determine whether it is pure numbers, test code as follows

The code is as follows Copy Code

#!/usr/bin/python
#-*-Coding:utf-8-*-

A = "1"
b = "1.2"
c = "a"
#通过抛出异常
def is_num_by_except (num):
Try
int (num)
Return True
Except ValueError:
# print '%s valueerror '% num
Return False

Print "by throwing an exception"
Print "A", is_num_by_except (a)
Print "B", is_num_by_except (b)
Print "C", Is_num_by_except (c)

Print "Through IsDigit ()"
Print "A", A.isdigit ()
Print "B", B.isdigit ()
Print "C", C.isdigit ()

Print "Through regular expressions"
Import re
Print "A", Re.match (R "d+$", a) and True or False
Print "B", Re.match (R "d+$", b) and True or False
Print "C", Re.match (R "d+$", c) and True or False
The output results are as follows:

By throwing an exception
A True
b False
C False
Through IsDigit ()
A True
b False
C False
Through regular expressions
A True
b False
C False
--eof--

To determine that a string contains only numeric characters

A: One method is A.isdigit (). However, this method is not valid for numeric strings that contain positive and negative numbers, so it is more accurate:

The code is as follows Copy Code

Try
x = Int (apossibleint)
... do something with x ...
Except ValueError:
... do something else ...

This is more accurate and more adaptable. But if you are convinced that there is no sign, it is more convenient to use the IsDigit () method of the string.

You can also use regular expressions:

The code is as follows Copy Code

Re.match (R ' [+-]?d+$ ', ' -1234′ ')

When the number is large, it may be faster than converting with type int.

Related Article

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.