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

Steven D'Aprano steve at REMOVETHIScyber.com.au
Thu Dec 22 17:03:55 EST 2005


On Thu, 22 Dec 2005 09:33:20 +0100, Peter Otten wrote:

> Steven D'Aprano wrote:
> 
>> On Wed, 21 Dec 2005 16:39:19 +0100, Daniel Schüle wrote:
>> 
>>> pinkfloydhomer at gmail.com wrote:
>>>> How do I check if a string contains (can be converted to) an int? I
>>>> want to do one thing if I am parsing and integer, and another if not.
>>>> 
>>>> /David
>>>> 
>>> 
>>> others already answered, this is just an idea
>>> 
>>>  >>> def isNumber(n):
>>> ...     import re
>>> ...     if re.match("^[-+]?[0-9]+$", n):
>>> ...             return True
>>> ...     return False
>> 
>> This is just a thought experiment, right, to see how slow you can make
>> your Python program run?
> 
> Let's leave the thought experiments to the theoretical physicists 

Didn't I have a smiley in there?


> and compare a regex with an exception-based approach:
> 
> ~ $ python -m timeit -s'import re; isNumber =
> re.compile(r"^[-+]\d+$").match' 'isNumber("-123456")'
> 1000000 loops, best of 3: 1.24 usec per loop

But since you're going to take my protests about regexes more seriously
than I intended you to, it is ironic that you supplied a regex that
is nice and fast but doesn't work:

>>> re.compile(r"^[-+]\d+$").match("123456") is None
True

Isn't that the point of Jamie Zawinski's quote about regexes? I too can
write a regex that doesn't solve the problem -- and this regex is a dead
simple case, yet still easy to get wrong.

BTW, you might find it informative to run timeit on the code snippet
provided by Daniel before reflecting on the context of my "how slow"
comment.



-- 
Steven.




More information about the Python-list mailing list