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

Dale Strickland-Clark dale at out-think.NOSPAMco.uk
Sun Nov 5 10:22:16 EST 2000


Gaute B Strokkenes <gs234 at cam.ac.uk> wrote:

>
>I've been using Python for something slightly more complicated than
>simple 'Hello World' programs for the first time in my life.  I find
>it very comfortable, but on the other hand I've also got this snippet
>in my program:
>
>def isanum(str):
>    # FIXME: Surely there must be a sane way of doing this.
>    from string import find, digits
>    for i in range(len(str)):
>        if find(digits, str[i]) == -1:
>            return 0
>    return 1
>
>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.

Here's a simple function to test for numeric.

def isanum(str):
	try:
		x = int(str)
		return 1
	except ValueError:
		return 0

However, rather than testing for numeric and then converting if the
test passes, just put the conversion inside an error handling block.
That would probably be more efficient.
--
Dale Strickland-Clark
Out-Think Ltd
Business Technology Consultants





More information about the Python-list mailing list