Identifying the data type of an input

2020-01-29 16:34发布

Hi 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. Appreciate any help

3条回答
2楼-- · 2020-01-29 17:13

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.

查看更多
可以哭但决不认输i
3楼-- · 2020-01-29 17:16

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'>
查看更多
萌系小妹纸
4楼-- · 2020-01-29 17:20
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'>
查看更多
登录 后发表回答