Recipe 16.1. Verifying Whether a String Represents a Valid NumberCredit: Gyro Funch, Rogier Steehouder ProblemYou need to check whether a string read from a file or obtained from user input has a valid numeric format. SolutionThe 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 DiscussionIf you insist, you can also perform this task with a regular expression: import re 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)) Having a regular expression to start from may be best if you need to 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 AlsoDocumentation for the re module and the float built-in module in the Library Reference and Python in a Nutshell. |