check to see if value can be an integer instead of string

gry at ll.mit.edu gry at ll.mit.edu
Tue Jan 17 22:01:34 EST 2006


nephish at xit.net wrote:
> Hello there,
> i need a way to check to see if a certain value can be an integer. I
> have looked at is int(), but what is comming out is a string that may
> be an integer. i mean, it will be formatted as a string, but i need to
> know if it is possible to be expressed as an integer.
The "int" builtin function never returns any value but an integer.

> like this
>
> var = some var passed to my script
> if var can be an integer :
>     do this
> else:
>     change it to an integer and do something else with it.

Be careful about thinking "change it to an integer" in python.  That's
not what happens.
The "int" builtin function looks at it's argument and, if possible,
creates a new integer object
that it thinks was represented by the argument, and returns that
integer object.

> whats the best way to do this ?

The "pythonic" way might be something like:

var=somestring
try:
   do_something(int(var))  #just try to convert var to integer and
proceed
except ValueError:
   do_something_else(var)  # conversion failed; do something with the
raw string value

The "int" builtin function tries to make an integer based on whatever
argument is supplied.
If if can not make an integer from the argument, it raises a ValueError
exception.
Don't be afraid of using exceptions in this sort of situation.  They
are pretty fast, and
ultimately clearer than a lot of extra "if" tests.

But do please always (unless you *really*really* know what you're
doing!) use a qualified
"except" clause.  E.g.

try:
   stuff
except SomeParticularException:
  other_stuff

Not:
try:
   stuff
except:
   other_stuff

The bare "except" clause invites all kinds of silent, unexpected bad
behavior.




More information about the Python-list mailing list