【问题标题】:How to check every data type from input in python?如何检查python输入中的每种数据类型?
【发布时间】:2021-01-05 00:06:55
【问题描述】:

简单,我想检查输入的string, integer or *any other type* 之类的数据类型。我们不知道类型,如果它是一个数字,我需要获取它的绝对值。但是,如果它是另一种类型,我对每种数据类型都有其他操作。例如,如果它是一个字符串打印字符串,或者它是一个像这样的浮点打印浮点数。我怎样才能以简单的方式解决这个问题?

在问这个问题之前,我已经尝试过:

def mainDataFunc():
    x = input("Anything: ")
    try:
        if type(abs(x)) is int:
            print("This is integer.")
        elif type(abs(x)) is float:
            print("This is float.")
        elif type(x) is str:
            print("This is string.")
    except ValueError:
        print("Type is not valid.")

【问题讨论】:

    标签: python python-3.x algorithm python-2.7


    【解决方案1】:

    这应该可行

    user_input = input("Enter something ")
    
    try:
        val = int(user_input)
        print("Input is an integer")
    except ValueError:
        try:
            val = float(user_input)
            print("Input is a float")
        except ValueError:
            print("It's a string")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-17
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多