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

PythonServer Side ProgrammingProgramming

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()
>>> x.isdigit()

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()
>>> bool(re.match('^[0-9]+$', x))

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

Updated on 30-Sep-2019 08:29:53