Check String Only Contains Numbers in Python

To check if a string only contains numbers,  use the built-in Python isnumeric() function. Pass the value before the function and isnumeric() will return True or False which you can store in a variable or use immediately.

 

val = '5'

result = val.isnumeric()

print(result)
True

 

If the string has any characters that are non-numerical isnumeric() will always return False.

 

val = 'four'

result = val.isnumeric()

print(result)
False