Pythonic way to determine if a string is a number

P

python

What's the Pythonic way to determine if a string is a number? By
number I mean a valid integer or float.

I searched the string and cMath libraries for a similar function
without success. I can think of at least 3 or 4 ways to build my
own function.

Here's what I came up with as a proof-of-concept. Are there
'better' ways to perform this type of test?

Thanks,
Malcolm

<code>
def isnumber( input ):
try:
if '.' in input:
num = float( input )
else:
num = int( input )
return True

except ValueError:
return False

if __name__ == '__main__':
tests = """
12
-12
-12.34
.0
.
1 2 3
1 . 2
just text
"""

for test in tests.split( '\n' ):
print 'test (%0s), isnumber: %1s' % \
( test.strip(), isnumber( test ) )

</code>
 
R

Roy Smith

What's the Pythonic way to determine if a string is a number? By
number I mean a valid integer or float.

try:
int(myString)
except ValueError:
print "That's bogus, man"
 
P

Paddy

What's the Pythonic way to determine if a string is a number? By
number I mean a valid integer or float.

I searched the string and cMath libraries for a similar function
without success. I can think of at least 3 or 4 ways to build my
own function.

Here's what I came up with as a proof-of-concept. Are there
'better' ways to perform this type of test?

Thanks,
Malcolm

<code>
def isnumber( input ):
    try:
        if '.' in input:
            num = float( input )
        else:
            num = int( input )
        return True

    except ValueError:
        return False

if __name__ == '__main__':
    tests = """
        12
        -12
        -12.34
        .0
        .
        1 2 3
        1 . 2
        just text
    """

    for test in tests.split( '\n' ):
        print 'test (%0s), isnumber: %1s' % \
          ( test.strip(), isnumber( test ) )

</code>

Their is a good answer given on Rosetta Code here:
http://www.rosettacode.org/wiki/IsNumeric#Python

- Paddy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top