Pythonic way to determine if a string is a number

Paddy O'Loughlin patrick.oloughlin at gmail.com
Tue Feb 17 10:35:18 EST 2009


2009/2/16 Python Nutter <pythonnutter at gmail.com>:
> silly me, forgot to mention
>
> build a set from digits + '.' and use that for testing.
>
> Cheers,
> PN
>
>
> 2009/2/16 Python Nutter <pythonnutter at gmail.com>:
>> Type casting seems to be the wrong way to go about this.
>>
>> teststring = '15719'
>> teststring.isdigit()
>> returns True
>>
>> That takes care of integers.
>>
>> from string import digits
>> digits
>> '0123456789'
>>
>> now you have all the digits and you can do set testing in your logic
>> to see if the teststring has anything in digits
>>
>> A dumb way to test is alphanumeric
>>
>> teststring2 = '105.22'
>> teststring2.isalnum()
>> returns True
>>
>> now you can go on from there and test to further to eliminate
>> 'abcd385laf8' which on alnum() also returns true.

Hmmm, this doesn't seem right to me.

Unless I'm missing something, won't your code think that "123.123.123"
is numeric? What about scientific or engineering notation with
exponents?

What's wrong with using python's own casting rules (given that you are
trying to emulate the way python behaves? Or, alternatively, using a
regular expression (as Nick Craig-Wood did).

Given these solutions, type-conversion and catching the ValueError
appears, to me, to be correct, the most concise, and the most readable
solution.

Of course, if you want to use your own set of rules for number
encoding, then building your own regular expression would seem to be
the right way to go.

Paddy

-- 
"Ray, when someone asks you if you're a god, you say YES!"



More information about the Python-list mailing list