How to check if a string "is" an int?

Dave Hansen iddw at hotmail.com
Wed Dec 21 10:35:43 EST 2005


On Thu, 22 Dec 2005 01:41:34 +1100 in comp.lang.python, Steven
D'Aprano <steve at REMOVETHIScyber.com.au> wrote:

[...]
>Well, let's find out, shall we?
[...]
>A small but consistent speed advantage to the try...except block.
>
>Having said all that, the speed difference are absolutely trivial, less
>than 0.1 microseconds per digit. Choosing one form or the other purely on
>the basis of speed is premature optimization.

Or maybe on which actually works.  LBYL will fail to recognize
negative numbers, e.g.

def LBYL(s):
    if s.isdigit():
        return int(s)
    else:
        return 0

def JDI(s):
    try:
        return int(s)
    except:
        return 0

test = '15'
print LBYL(test), JDI(test)   #-> 15 15

test = '-15'
print LBYL(test), JDI(test)   #-> 0 -15

>
>But the real advantage of the try...except form is that it generalises to
>more complex kinds of data where there is no fast C code to check whether

re: Generalization, apropos a different thread regarding the %
operator on strings.  In Python, I avoid using the specific type
format conversions (such as %d) in favor of the generic string
conversion (%s) unless I need specific field width and/or padding or
other formatting, e.g.

   for p in range(32):
	v = 1<<p
	print "%2u %#010x : %-d" % (p,v,v)

Regards,
                                        -=Dave

-- 
Change is inevitable, progress is not.



More information about the Python-list mailing list