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

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Jan 18 06:29:59 EST 2006


On Tue, 17 Jan 2006 18:02:52 -0800, nephish 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. 

Not in Python it isn't. int(value) returns an int, not a string.

> i mean, it will be formatted as a string, but i need to
> know if it is possible to be expressed as 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.


So, let's see if I understand your problem: 

if var can be an integer, you "do this" (whatever this is).

If var *can't* be an integer, you change it to an integer anyway.



> whats the best way to do this ?


try:
    int(var)
except ValueError:
    raise
else:
    do_this()


Or even simpler:

int(var)
do_this()


-- 
Steven.




More information about the Python-list mailing list