[Python-talk] Does a string contain an integer

Dick Moores rdmoores at gmail.com
Thu Apr 3 19:17:30 EDT 2008


On Thu, Apr 3, 2008 at 4:01 PM, Lloyd Kvam <lkvam at venix.com> wrote:
>
>
> On Thu, 2008-04-03 at 12:49 -0700, Dick Moores wrote:
> > On Thu, Apr 3, 2008 at 7:49 AM, Lloyd Kvam <lkvam at venix.com> wrote:
> > >
> > > On Wed, 2008-04-02 at 23:05 -0700, Dick Moores wrote:
> > >
> > > > On Wed, Apr 2, 2008 at 9:06 AM, Lloyd Kvam <lkvam at venix.com> wrote:
> > > > I'll keep this function around:
> > > >
> > > > def str_is_int(astr):
> > > >     try:
> > > >         int(astr)
> > > >         return True
> > > >     except:
> > > >         return False
> > > >
> > > Still if your code looks like
> > >
> > > if str_is_int(astr):
> > >    aint = int(astr)
> > > else:
> > >    handle_not_an_int(astr)
> > >    ???
> > >
> > > wouldn't you be just as well off coding the try / except ValueError
> > > directly?
> >
> > I just wanted the function in my toolbox. I don't have any code right
> > now to apply it to.
> >
> > > try:
> > >    aint = int(astr)
> > > except ValueError:
> > >    handle_not_an_int(astr)
> >
> > Could you expand on that a bit? What does the 4th line mean?
>
> Sorry about beating this to death.  I had one last thought about
> wrapping the try/except in a function.
>
> This is the default Python error handling:
> int('a')
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> ValueError: invalid literal for int() with base 10: 'a'
>
>
> Perhaps you'd like like a better error message.  A function like
> def str2int(astr):

??

Dick


More information about the Python-talk mailing list