How can I tell when a string is in fact a number?
dale at out-think.NOSPAMco.uk
Sun Nov 5 16:22:16 CET 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:
> # 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.
x = int(str)
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.
Business Technology Consultants
More information about the Python-list