check to see if value can be an integer instead of string
Claudio Grondi
claudio.grondi at freenet.de
Tue Jan 17 21:23:23 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.
>
> 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.
>
> whats the best way to do this ?
>
> thanks, shawn
>
No idea whats the best way to do and what in detail you want to achieve,
but before others reply here, you can maybe start with something like this:
intTheInt = None
def checkIfStringCanBeAnInteger(strWithInt):
global intTheInt
try:
intTheInt = int(strWithInt)
if(type(intTheInt)==type(1)):
return True
except:
return False
#:def
lstTestCases = [
'123', '789' , 'no', '1is2'
]
for strWithInt in lstTestCases:
intTheInt = None
if checkIfStringCanBeAnInteger(strWithInt):
print '"'+strWithInt+'"', ' is an integer', intTheInt
else:
print '"'+strWithInt+'"', ' is NOT an integer'
Claudio
More information about the Python-list
mailing list