Identifying the data type of an input
Asked Answered
F

4

7

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.

Faunie answered 5/3, 2014 at 13:52 Comment(0)
B
14
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'>
Bartz answered 5/3, 2014 at 14:1 Comment(2)
only Boolean values are still taken as strings. Any Idea?Faunie
@ApeironKambyses Do the boolean values have initial capital letters?Bartz
S
4

input() will always return a string. If you want to see if it is possible to be converted to an integer, you should do:

try:
    int_user_var = int(user_var)
except ValueError:
    pass # this is not an integer

You could write a function like this:

def try_convert(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            try:
                return bool(s)
            except ValueError:
                return s

However, as mentioned in the other answers, using ast.literal_eval would be a more concise solution.

Syd answered 5/3, 2014 at 13:53 Comment(3)
do I have to use "if statements" to determine every single type and try to convert them to Booleans, floats etc?Faunie
Yes, you will have to do that.Syd
bool(s) is True for every non-empty string. Without literal_eval you'd have to use a string comparison for "True" and "False".Ellingson
P
1

Input will always return a string. You need to evaluate the string to get some Python value:

>>> type(eval(raw_input()))
23423
<type 'int'>
>>> type(eval(raw_input()))
"asdas"
<type 'str'>
>>> type(eval(raw_input()))
1.09
<type 'float'>
>>> type(eval(raw_input()))
True
<type 'bool'>

If you want safety (here user can execute arbitrary code), you should use ast.literal_eval:

>>> import ast
>>> type(ast.literal_eval(raw_input()))
342
<type 'int'>
>>> type(ast.literal_eval(raw_input()))
"asd"
<type 'str'>
Ponzo answered 5/3, 2014 at 13:57 Comment(7)
From the question I'm using python 3.2.3Bartz
This is very dangerous if the user input is import os; os.system("rm -rf *").Syd
@TomLeese no it's not, you are probably thinking of exec and not evalNablus
Ok, you are correct that you would not be able to import os, but you could still run os.system("rm -rf *") if it was already imported.Syd
@Tom Leese: see my edit. I didn't write it at first because I didn't remember in with module the literal_eval function was.Ponzo
Thanks everybody. You all have been very helpfulFaunie
eval('__import__("os").listdir(".")'). Don't use eval. Even if you use CPython's ability to set __builtins__, someone can always find a way back to builtins.Ellingson
A
-1

The problem here is that any input is taken a 'string'. So we need to treat 'string' as a special case, and keep it separate from everything else.

x = input("Enter something: ")

try:
    if type(eval(x)) == float:
        print(x, " is floating point number")
    elif type(eval(x)) == int:
        print(x, " is interger number")    
    elif type(eval(x)) == bool:
        print(x, " is a boolean")      
except:
    print("That is a string")

Here the input is first evaluated. If it's anything other than a string, the eval function shall show the type. If it's a string, it is considered as an "error", and the error message is given as "That is a string".

Aten answered 17/5, 2020 at 12:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.