Pythonic way to determine if a string is a number
paddy3118 at googlemail.com
Tue Feb 17 07:34:49 CET 2009
On Feb 15, 5:46 pm, pyt... at bdurham.com wrote:
> 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?
> def isnumber( input ):
> if '.' in input:
> num = float( input )
> num = int( input )
> return True
> except ValueError:
> return False
> if __name__ == '__main__':
> tests = """
> 1 2 3
> 1 . 2
> just text
> for test in tests.split( '\n' ):
> print 'test (%0s), isnumber: %1s' % \
> ( test.strip(), isnumber( test ) )
Their is a good answer given on Rosetta Code here:
More information about the Python-list