Recipe 16.1. Verifying Whether a String Represents a Valid Number
Credit: Gyro Funch, Rogier Steehouder
Problem
You need to check whether a
string read from a file or obtained from user input has a valid
numeric format.
Solution
The simplest and most Pythonic approach is to "try
and see":
def is_a_number(s):
try: float(s)
except ValueError: return False
else: return True
Discussion
If you insist, you can also perform this task with a regular
expression:
import reHaving a regular expression to start from may be best if you need to
num_re = re.compile
(r''^[-+]?([0-9]+\.?[0-9]*|\.[0-9]+)([eE][-+]?[0-9]+)?$'')
def is_a_number(s):
return bool(num_re.match(s))
be tolerant of certain specific variations, or to pick up numeric
substrings from the middle of larger strings. But for the specific
task posed as this recipe''s Problem,
it''s simplest and best to "let
Python do it!"
See Also
Documentation for the re module and the
float built-in module in the Library
Reference and Python in a
Nutshell.