Input Data Type Identification

Hi, I am trying to print a user input data type and create a table as shown below:

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

etc. I am using python 3.2.3 and I know that I can use type () to get the data type, but in python all user inputs are accepted as strings, and I don't know how to determine if the input string is either a Boolean or an integer or float . Here is this piece of code:

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

which always returns str for the string. Appreciate any help

+4
source share
3 answers
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'>
+7
source

input() . , , :

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

​​:

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

, , ast.literal_eval .

+3

Input always returns a string. You need to evaluate the string to get the 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 need security (here the 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'>
+2
source

Source: https://habr.com/ru/post/1530253/


All Articles