How to find the type ...

Steve Holden steve at holdenweb.com
Fri Dec 9 11:55:43 EST 2005


Lad wrote:
> Hello
> How can I find out in Python whether the operand is integer or a
> character  and change from char to int ?
> Regards,
> L.
> 
Easiest would just be to apply the int() type function to whatever you 
have and trap any resulting exception.

  >>> getInt(1)
1
  >>> getInt("32767")
32767
  >>> getInt('have a banana')
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 5, in getInt
ValueError: getInt called with non-integer value

Unfortunately we should also consider:


  >>> getInt("3.14159")
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 5, in getInt
ValueError: getInt called with non-integer value
  >>> getInt(3.14159)
3
  >>>

which may or may not be what you want.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list