How can I tell when a string is in fact a number?

Julio Flores Schwarzbeck jflores at codeit.com
Mon Nov 6 13:08:07 EST 2000


def isnum(data): # needs string module to be loaded in
     for x in range(len(data)):
         if not (data[x] in tuple(string.digits) or data[x] in '.'):
             return 0
     return 1



At 06:04 PM 11/5/00 +0000, Gaute B Strokkenes wrote:
>Paul Prescod <paulp at ActiveState.com> writes:
>
> > On 5 Nov 2000, Gaute B Strokkenes wrote:
> > >
> > > def isanum(str):
> > >
> > > As the comment says, I'm sure there must be a more straightforward way
> > > to do this.  However, I can't find out how, though I'm sure that it is
> > > really my relative unfamiliarity with Python that is to blame.
> >
> > There may be a more elegant way to do it, but:
> >
> > def isanum(num):
> >     try:
> >         int(num)
> >         return 1
> >     except ValueError:
> >         return 0
>
>Thanks.  I must admit that expected there to be a simple function to
>do this, though...
>
>--
>Big Gaute                               http://www.srcf.ucam.org/~gs234/
>There's a lot of BIG MONEY in MISERY if you have an AGENT!!
>--
>http://www.python.org/mailman/listinfo/python-list





More information about the Python-list mailing list