Search code examples
pythonpython-3.xtypesuser-input

Identifying the data type of an input


I am trying to print the data type of a user input and produce a table like following:

ABCDEFGH = String
1.09 = float
0 = int
true = bool

etc.

I'm using Python 3.2.3 and I know I could use type() to get the type of the data but in Python all user inputs are taken as strings and I don't know how to determine whether the input is a string or Boolean or integer or float. Here is that part of the code:

user_var = input("Please enter something: ")
print("you entered " + user_var)
print(type(user_var))

which always returns str for string.


Solution

  • from ast import literal_eval
    
    def get_type(input_data):
        try:
            return type(literal_eval(input_data))
        except (ValueError, SyntaxError):
            # A string, so return str
            return str
    
    print(get_type("1"))        # <class 'int'>
    print(get_type("1.2354"))   # <class 'float'>
    print(get_type("True"))     # <class 'bool'>
    print(get_type("abcd"))     # <class 'str'>