Computer >> Computer tutorials >  >> Programming >> Python

How do I check if raw input is integer in Python 3?


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. Even if you input a float, it'll return false. You can call it as follows:

>>> x = raw_input()
12345
>>> x.isdigit()
True

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]+$". For example,

>>> x = raw_input()
123abc
>>> bool(re.match('^[0-9]+$', x))
False

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