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.