原文:Python Print Type of Variable – How to Get Var Type,作者:Kolade Chris

如果你是一个 Python 初学者,你一开始可能会对它的各种数据类型感到很困惑。毕竟,在这门语言中,有很多类型可供你使用。

在这篇文章中,我将向你展示如何在 Python 中通过赋值给一个变量来获得各种数据结构的类型,然后用 print() 函数将该类型打印到控制台。

如何在 Python 中打印一个变量的类型

要在 Python 中获得一个变量的类型,可以使用内置的 type() 函数。

基本的语法是这样的:

type(variableName)

在 Python 中,所有东西都是一个对象。所以,当你使用 type() 函数将存储在一个变量中的值的类型打印到控制台时,它返回对象的类类型。

例如,如果类型是一个字符串,你对它使用 type() ,你会得到 <class ‘string‘> 这个结果。

为了向你展示 type() 函数的作用,我将声明一些变量并将 Python 中的各种数据类型分配给它们。

name = "freeCodeCamp"

score = 99.99

lessons =  ["RWD", "JavaScript", "Databases", "Python"]

person = {
    "firstName": "John",
    "lastName": "Doe",
    "age": 28
}

langs = ("Python", "JavaScript", "Golang")

basics = {"HTML", "CSS", "JavaScript"}

然后,我将通过将 print() 包裹在一些字符串和 type() 函数上,将这些类型打印到控制台。

print("The variable, name is of type:", type(name))
print("The variable, score is of type:", type(score))
print("The variable, lessons is of type:", type(lessons))
print("The variable, person is of type:", type(person))
print("The variable, langs is of type:", type(langs))
print("The variable, basics is of type:", type(basics))

这是结果

# Outputs:
# The variable, name is of type:  <class 'str'>
# The variable, score is of type: <class 'float'>  
# The variable, lessons is of type:  <class 'list'>
# The variable, person is of type:  <class 'dict'> 
# The variable, langs is of type:  <class 'tuple'> 
# The variable, basics is of type:  <class 'set'>  

小结

type() 函数是 Python 中的一个很棒的内置函数,用它可以得到一个变量的数据类型。

如果你是一个初学者,你应该通过使用 type() 函数将一个变量的类型打印到控制台,来节省填塞数据类型的麻烦。这将为你节省一些时间。

你还可以使用 type() 函数进行调试,因为在 Python 中,变量没有用数据类型来声明。所以,type() 函数是内置在语言中的,供你检查变量的数据类型。

谢谢阅读本文。