如何创建数据类型标识符



我需要一个小任务的帮助,我刚开始学习Python。。。我想创建一个数据类型标识符,其中如果我键入int,它将输出";它是一个int";如果我键入一个字符串,它将输出"0";它是一个字符串";,基本上。。。

到目前为止,这是我的代码:

input_data = (input())
data_calculator = (type(input_data))
if data_calculator == str:
print("It is a String")
elif data_calculator == float:
print("It is a float")
elif data_calculator == int:
print("It is an int")
else:
print("Error mate...")

我认为问题是当我在控制台中键入时,它将int和float视为str.

电流输出:

当我键入Int或float时,它会一直输出,";它是一个字符串";

感谢任何帮助,谢谢

input总是返回一个str值,但您可以检查是否可以执行强制转换,但会出现异常。

这里有一个片段可以做到这一点:

def check_type(_type, val):
try:
x = _type(val)
return True
except:
return False
def find_type(val):
for _type in [int, float, complex]:
if check_type(_type, val):
return _type
if val in ['True' ,'False']:
return bool
return str
if __name__ == "__main__":
while True:
s = input("s = ? ")
t = find_type(s)
print("The value of string s has type", t.__name__)

带有一些测试字符串的输出为:

s = ? 5
The value of string s has type int
s = ? 3.14
The value of string s has type float
s = ? 1+2j
The value of string s has type complex
s = ? False
The value of string s has type bool
s = ? foo
The value of string s has type str

相关内容

最新更新