Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources] - نسخه متنی

David Ascher, Alex Martelli, Anna Ravenscroft

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید


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
.

/ 394