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.