Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if raw input is integer in python 2.7?

Is there a method that I can use to check if a raw_input is an integer?

I found this method after researching in the web:

print isinstance(raw_input("number: ")), int)

but when I run it and input 4 for example, I get FALSE. I'm kind of new to python, any help would be appreciated.

like image 915
Alejandro Veintimilla Avatar asked Oct 18 '13 03:10

Alejandro Veintimilla


People also ask

How do you check if an input is an integer in Python?

To check if the variable is an integer in Python, we will use isinstance() which will return a boolean value whether a variable is of type integer or not. After writing the above code (python check if the variable is an integer), Ones you will print ” isinstance() “ then the output will appear as a “ True ”.

How do you tell if an input is an integer?

Apply isdigit() function that checks whether a given input is numeric character or not. This function takes single argument as an integer and also returns the value of type int.

How do you check if a number is integer or string in Python?

Python String isnumeric() Method The isnumeric() method returns True if all the characters are numeric (0-9), otherwise False. Exponents, like ² and ¾ are also considered to be numeric values. "-1" and "1.5" are NOT considered numeric values, because all the characters in the string must be numeric, and the - and the .

How do you check if an element in a string is an integer?

To check if a string is integer in Python, use the isdigit() method. The string isdigit() is a built-in Python method that checks whether the given string consists of only digits.


1 Answers

isinstance(raw_input("number: ")), int) always yields False because raw_input return string object as a result.

Use try: int(...) ... except ValueError:

number = raw_input("number: ")
try:
    int(number)
except ValueError:
    print False
else:
    print True

or use str.isdigit:

print raw_input("number: ").isdigit()

NOTE The second one yields False for -4 because it contains non-digits character. Use the second one if you want digits only.

UPDATE As J.F. Sebastian pointed out, str.isdigit is locale-dependent (Windows). It might return True even int() would raise ValueError for the input.

>>> import locale
>>> locale.getpreferredencoding()
'cp1252'
>>> '\xb2'.isdigit()  # SUPERSCRIPT TWO
False
>>> locale.setlocale(locale.LC_ALL, 'Danish')
'Danish_Denmark.1252'
>>> '\xb2'.isdigit()
True
>>> int('\xb2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '\xb2'
like image 139
falsetru Avatar answered Oct 18 '22 15:10

falsetru