Best way to check if string is an integer?

Jorgen Grahn grahn+nntp at snipabacken.se
Sun Apr 6 02:52:18 EDT 2008


On Sat, 5 Apr 2008 22:02:10 -0700 (PDT), Paddy <paddy3118 at googlemail.com> wrote:
> 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:

>> > 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?

> 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.

int('5.0') raises an exception rather than rounding or truncating to
5. That is probably what most people want, and it seems the original
poster wanted that, too.

I always use int(n). If I ever find a situation where I want another
syntax for integers for some specialized use, I'll approach it as a
normal parsing problem and use regexes and so on -- wrapped in a
function.

The problem becomes clearer if you look at floats. There are many
different ways to write a float[0], and Python parses them better and
faster than you and me.

/Jorgen

[0] There would have been more if Python had supported hexadecimal
    floating-point literals, like (I believe) C does.

-- 
  // Jorgen Grahn <grahn@        Ph'nglui mglw'nafh Cthulhu
\X/     snipabacken.se>          R'lyeh wgah'nagl fhtagn!



More information about the Python-list mailing list