Fix Python – How do you check in python whether a string contains only numbers?


Asked By – Coder77

How do you check whether a string contains only numbers?

I’ve given it a go here. I’d like to see the simplest way to accomplish this.

import string

def main():
    isbn = input("Enter your 10 digit ISBN number: ")
    if len(isbn) == 10 and string.digits == True:
        print ("Works")
        print("Error, 10 digit number was not inputted and/or letters were inputted.")

if __name__ == "__main__":
    input("Press enter to exit: ")

Now we will see solution for issue: How do you check in python whether a string contains only numbers?


You’ll want to use the isdigit method on your str object:

if len(isbn) == 10 and isbn.isdigit():

From the isdigit documentation:


Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

This question is answered By – mhlester

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0