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

Peter Otten __peter__ at web.de
Thu Dec 22 03:33:20 EST 2005


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 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
~ $ python -m timeit -s'import re; isNumber =
re.compile(r"^[-+]\d+$").match' 'isNumber("-123456x")'
1000000 loops, best of 3: 1.31 usec per loop

~ $ python -m timeit -s'def isNumber(n):' -s'  try: int(n); return True' -s
'  except ValueError: pass' 'isNumber("-123456")'
1000000 loops, best of 3: 1.26 usec per loop
~ $ python -m timeit -s'def isNumber(n):' -s'  try: int(n); return True' -s
'  except ValueError: pass' 'isNumber("-123456x")'
100000 loops, best of 3: 10.8 usec per loop

A tie for number-strings and regex as a clear winner for non-numbers.

Peter




More information about the Python-list mailing list