识别输入的数据类型 [英] Identifying the data type of an input

查看:57
本文介绍了识别输入的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打印用户输入的数据类型并生成如下表格:

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

ABCDEFGH = 字符串,1.09 = 浮点数,0 = 整数,真 = 布尔值

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

等.我正在使用 python 3.2.3,我知道我可以使用 type() 来获取数据的类型,但在 python 中,所有用户输入都被视为字符串,我不知道如何确定输入是字符串还是布尔值或整数或浮点数.这是代码的那部分:

, 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))

总是为字符串返回 str .感谢任何帮助

which always returns str for string. Appreciate any help

推荐答案

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'>

这篇关于识别输入的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆