How to check if a string "is" an int?

Erik Max Francis max at alcyone.com
Wed Dec 21 16:55:47 EST 2005


Neuruss wrote:

> Can't we just check if the string has digits?
> For example:
> 
>>>> x = '15'
>>>> if x.isdigit():
> 	print int(x)*3
> 
> 	
> 45

 >>> x = '-1'
 >>> if x.isdigit(): print int(x)*3
...

To make sure you get it right, you'll have to do exactly what the Python 
parser does in order to distinguish integer literals from other tokens. 
  Taken to the extreme for other types, such as floats, you're far 
better off just using the internal mechanisms that Python itself uses, 
which means to try to convert it and catch any exception that results 
from failure.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   Make it come down / Like molasses rain
   -- Sandra St. Victor



More information about the Python-list mailing list