Search code examples
pythonstringpython-2.xisinstance

How do I check if an input is a string or int in Python 2.x?


I am trying to check if an input is a word or a number.

var = input("var: ")

if isinstance(var, str):
    print "var = word"

else:
   print "var = number"

This is the code I came up with but sadly doesn't work; I'm new to python and programming in general so I don't know alot of commands, any suggestion would be appreciated ^^


Solution

  • input() will take and evaluate your input before handing it over to you. That is, if the user enters exit(), your application will exit. This is undesirable from a standpoint of security. You would want to use raw_input() instead. In this case you can expect the returned value to be a string.

    If you still want to check if the strings content is convertible to a (integer) number, please follow the approach discussed here:

    A short outline: Just try to convert it to a number and see if it fails.

    Example (untested):

    value = raw_input()
    try:
        int(value)
        print "it's an integer number"
    except ValueError:
        print "it's a string"
    

    For reference:

    Note that the semantics of the input() function change with Python 3: