How to check if a Python string contains only digits?



There is a method called isdigit() in String class that returns true if all characters in the string are digits and there is at least one character, false otherwise. You can call it as follows −

Example

print("12345".isdigit())
print("12345a".isdigit())

Output

True
False

You can also use regexes for the same result. For matching only digits, we can call the re.match(regex, string) using the regex: "^[0-9]+$". 

example

import re
print(bool(re.match('^[0-9]+$', '123abc')))
print (bool(re.match('^[0-9]+$', '123')))

Output

False
True

re.match returns an object, to check if it exists or not, we need to convert it to a boolean using bool().


Advertisements