Simple tests using Exceptions

Exceptions provide very handy ways of performing simple tests. For example, if you want to know if the contents of a string represent an integer, why not just try to convert it? That's what IsInt() does.


Similar tests can be written for types other than Integer. Exceptions provide a direct way of performing tests that could otherwise be quite laborious.

It should be noted that this "type" test is semantically quite different from testing whether a string contains digits. IsAllDigits() will help you there.

def IsInt( str ):
	""" Is the given string an integer?	"""
	ok = 1
	try:
		num = int(str)
	except ValueError:
		ok = 0
	return ok

def IsAllDigits( str ):
	""" Is the given string composed entirely of digits? """
	import string
	match = string.digits
	ok = 1
	for letter in str:
		if letter not in match:
			ok = 0
			break
	return ok

if __name__ == '__main__':
	print IsInt('23')
	print IsInt('sd')
	print IsInt('233835859285')
	print IsAllDigits('233835859285')

code.activestate.com ↗