As pointed out in this comment How do you check in python whether a string contains only numbers? the isdigit()
method is not totally accurate for this use case, because it returns True for some digit-like characters:
>>> "\u2070".isdigit() # unicode escaped 'superscript zero'
True
If this needs to be avoided, the following simple function checks, if all characters in a string are a digit between "0" and "9":
import string
def contains_only_digits(s):
# True for "", "0", "123"
# False for "1.2", "1,2", "-1", "a", "a1"
for ch in s:
if not ch in string.digits:
return False
return True
Used in the example from the question:
if len(isbn) == 10 and contains_only_digits(isbn):
print ("Works")