Best way to check if string is an integer?

Paddy paddy3118 at googlemail.com
Sun Apr 6 01:02:10 EDT 2008


On Apr 6, 5:18 am, ernie <ernesto.ado... at gmail.com> wrote:
> On Apr 6, 10:23 am, Roy Smith <r... at panix.com> wrote:
>
>
>
> > In article <mailman.2927.1207447793.9267.python-l... at python.org>,
> >  Steve Holden <st... at holdenweb.com> wrote:
>
> > > > This doesn't cater for negative integers.
>
> > > No, it doesn't, but
>
> > > s.isdigit() or (s[0] in "+-" and s[1:].isdigit) # untested
>
> > > does.
>
> > I think this fails on "   -1".  So, then you start doing
> > s.strip().isdigit(), and then somebody else comes up with some other
> > unexpected corner case...
>
> > int(s) and catching any exception thrown just sounds like the best way.
>
> Another corner case: Is "5.0" an integer or treated as one?
>
> regards,
> ernie

In Python, 5.0 is a float "5.0" is a string, and you need to make your
mind up about what type you want "5.0" to be represented as in your
program and code accordingly.

- Paddy.



More information about the Python-list mailing list