Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources]

David Ascher, Alex Martelli, Anna Ravenscroft

نسخه متنی -صفحه : 394/ 309
نمايش فراداده

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 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 Also

Documentation for the re module and the float built-in module in the Library Reference and Python in a Nutshell.