Pythonic way to determine if a string is a number
python at bdurham.com
python at bdurham.com
Sun Feb 15 15:05:01 EST 2009
Thanks for everyone's feedback. I believe my original post's code
(updated following my signature) was in line with this list's feedback.
Christian: Thanks for reminding me about exponential formats. My updated
code accounts for these type of numbers. I don't need to handle inf or
nan values. My original code's except catches an explicit ValueError
exception per your concern about bare excepts.
Malcolm
<code>
# str_to_num.py
def isnumber( input ):
try:
num = float( input )
return True
except ValueError:
return False
if __name__ == '__main__':
tests = """
12
-12
-12.34
.0
.
1 2 3
1 . 2
1e10
1E10
inf
nan
12 and text
just text
"""
for test in tests.split( '\n' ):
print 'test (%0s), isnumber: %1s' % ( test.strip(), isnumber(
test ) )
</code>
More information about the Python-list
mailing list