OneBite.Dev - Coding blog in a bite size

check if a string contains only numbers in python

Code snippet on how to check if a string contains only numbers in python

def is_digit(string):
    if string.isdigit():
        return True
    else:
        return False

This code contains a function called is_digit which takes one parameter, a string. Inside the function there is an if statement which checks whether the string is all made up of digits, by calling the string’s isdigit() function. If it is true then the function will return True back to the caller, otherwise it returns False. This can be helpful when it’s necessary to make sure that a string contains only numbers in Python.

python