This article mainly introduces python's method of determining whether a string is a pure number. it uses the isdigit method to determine whether the string is a pure number. It also provides improved examples and regular expression-based judgment usage, which has some reference value, for more information about how to determine whether a string is a pure number, see the example in this article. Share it with you for your reference. The details are as follows:
The code to be judged is as follows. The difference between positive and negative numbers cannot be distinguished through exception judgment. Regular expressions can be written flexibly based on your own needs. the isdigit method is used to determine whether the code is a pure number. the test code is as follows:
The code is as follows:
#! /Usr/bin/python
#-*-Coding: UTF-8 -*-
A = "1"
B = "1.2"
C = ""
# Throw an exception
Def is_num_by_except (num ):
Try:
Int (num)
Return True
Failed T ValueError:
# Print "% s ValueError" % num
Return False
Print "throw an exception"
Print "a", is_num_by_t T ()
Print "B", is_num_by_t T (B)
Print "c", is_num_by_t T (c)
Print "via isdigit ()"
Print "a", a. isdigit ()
Print "B", B. isdigit ()
Print "c", c. isdigit ()
Print "using 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 result is as follows:
The code is as follows:
Throw an exception
A True
B False
C False
Use isdigit ()
A True
B False
C False
Regular expression
A True
B False
C False
-- EOF --
Determines whether a string contains only numeric characters.
One method is a. isdigit (). However, this method is invalid for numeric strings containing positive and negative numbers. Therefore, it is more accurate:
The code is as follows:
Try:
X = int (aPossibleInt)
... Do something with x...
Failed T ValueError:
... Do something else...
This is more accurate and more suitable. However, if you are sure that there are no plus or minus signs, it is more convenient to use the isdigit () method of the string.
You can also use a regular expression:
The code is as follows:
Re. match (r' [+-]? D + $','-1234 ′)
When the number is large, it may be faster than int type conversion.
I hope this article will help you with Python programming.