Checking var is a number?
Fredrik Lundh
fredrik at pythonware.com
Tue Jun 6 05:28:51 EDT 2006
dav.phillips at ntlworld.com wrote:
> I am very new to all this and need to know how to check
> a variable to see if it is a number or not.
assuming that "variable" means "string object" and "number" means
"integer", you can use the isdigit predicate:
if var.isdigit():
print "all characters in", var, "are digits"
if you want to check for anything that can be converted to a float, the
best way is to do the conversion and trap any ValueError that may occur:
try:
value = float(var)
except ValueError:
print "not a valid float"
if you want an integer instead, replace "float" with "int".
if you had something else in mind, let us know.
> Also can anyone recommend a reference book apart from dive into python
> preferably a reference with good examples of how to impliment code.
you can find an extensive list of available books here:
http://wiki.python.org/moin/PythonBooks
some on-line code collections:
http://aspn.activestate.com/ASPN/Python/Cookbook/
http://effbot.org/zone/librarybook-index.htm
and don't forget the core references:
http://docs.python.org/lib/
http://docs.python.org/ref/
</F>
More information about the Python-list
mailing list