Welcome, guest | Sign In | My Account | Store | Cart

Many times I needed to check if a string represented a number or not. This is a very short recipe that uses Python int() function to do the check, instead of looping on the single characters.

Python, 21 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# Check that string 'source' represents an integer

try:
    stripped = str(int(source))
except:
    # 'source' does not represent an integer
    .....

# Additionally, it's easy to check if 'source' has blanks around the number
if source != stripped:
    # 'source' has blanks before or after the number, or both
    .....



# A simpler version if you don't need the stripped value:
try:
    dummy = int(source)
except:
    # 'source' does not represent a number
    .....

This recipe is the obvious consequence of the standard practice of putting a string-to-int convertion in a try-except statement to avoid non-integer strings, when it is not important to use the numeric value, but the string value.

Before using this recipe, I used to loop on all characters of source until I found one which was not a digit, or until I reached the end of the source string.

This implementation is surely faster, shorter and more robust.

3 comments

Ian Bicking 17 years, 3 months ago  # | flag

More permissive. In a language like PHP, the integer value of a string like "123 blah blah" is 123; it ignores extra text. You can do this in Python as well, assuming you require whitespace after the number, like:

try:
    number = int(source.strip().split()[0])
except (ValueError, IndexError):
    number = None

''.split() returns [], so you may get an IndexError when the string is empty or contains only whitespace.

Andrew Dalke 17 years, 2 months ago  # | flag

ValueError. don't use a bare "except:", use "except ValueError".

Why? Well, I've done that and managed to mistype the variable name. The resulting NameError was caught mistakenly.

Also consider what happens if someone hits KeyboardInterrupt in the middle of that try block. It gets ignored.

james 7 years, 9 months ago  # | flag

I just use translate function to strip all numbers out of string to test if it is a number.

>>> import string
>>> def isdigits(s):
...     idtrans=string.maketrans('0123456789','xxxxxxxxxx')
...     sint=s.translate(idtrans).strip('x')
...     if sint:
...             return False
...     else:
...             return True
... 
>>> isdigits('t12345')
False
>>> isdigits('12345')
True
>>>
Created by Francesco Ricciardi on Sun, 5 Sep 2004 (PSF)
Python recipes (4591)
Francesco Ricciardi's recipes (1)
Python Cookbook Edition 2 (117)

Required Modules

  • (none specified)

Other Information and Tasks