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.
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.
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:
''.split() returns [], so you may get an IndexError when the string is empty or contains only whitespace.
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.
I just use translate function to strip all numbers out of string to test if it is a number.