[Python-talk] Does a string contain an integer

Dick Moores rdmoores at gmail.com
Thu Apr 3 18:58:42 EDT 2008


On Thu, Apr 3, 2008 at 3:46 PM, Lloyd Kvam <python at venix.com> wrote:

> ---- case 1 ----
> # we let the ValueError happen
> aint = int(astr)        # raises ValueError if it can't be converted
> print "You've won %d Dollars" % aint
>
> somewhere earlier in your code you have a try / except that will deal
> with the error.
>
> Or maybe you don't.  Perhaps there is a GUI that provides a list of
> valid strings, but somehow they managed to feed in an invalid string.
> You've decided to simply let the program die on the unhandled exception.
> ------------------
>
> ---- case 2 ----
> if str_is_int(astr):
>        aint = int(astr)
>        # True case handler
>        # do something with the integer value
> else:
>        # False case handler
>        # presumably you provide an error message
>
> To my mind, you only use the str_is_int function if you are concerned
> with doing something when the conversion would fail.
> ----------------------------------
> But I don't think that function provides much benefit.  You could just
> as easily code case 2 to look like:
>
> try:    #keep try block small by using else
>        aint = int(astr)
> except ValueError:
>        # False case handler
>        # presumably you provide an error message
> else:
>        # True case handler - astr was converted to an int
>        # do something with the integer value
>
> If you choose to use a default value for the integer when the string is
> defective, you could code
>
> try:
>        aint = int(astr)
> except ValueError:
>        aint = 0        # or some other default
> print "You've won %d Dollars" % aint
>
>
>
> Ideally, your error handling was put in place earlier and most of the
> time you simply code
>        aint = int(astr)
>
> If the error handling needs to be addressed here, I still see no benefit
> to putting the try/except logic into a function that returns a boolean.
> The Python try / except / else control statements seem to be the right
> tools for the job.

Thanks for spelling out your reasoning.

Dick


More information about the Python-talk mailing list