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

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Thu Jan 19 18:06:16 EST 2006


In <dqk8r0$ou2$1 at newsreader3.netcologne.de>, Claudio Grondi wrote:

> 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

Please!  Don't use ``global``.  And why are you testing for type `int` if
you converted successfully to `int` just one line above!?

Also it's not a good idea to use a bare ``except``.  If you mistype a name
within the ``try...except`` the function will alwas return false because
the `NameError` is caught.  The ``except`` will mask *any*
exception/error.  This makes debugging more difficult than it should be.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list