带有示例的Python类型函数

Python provides a lot of different types for programming purposes. While using these structs we may need to decide which variable or identifier is which type. Python provides builtin type function in order to decide given identifier types. We just need to provide the identifier to the type function.

Python为编程目的提供了许多不同的类型。 在使用这些结构时,我们可能需要确定哪个变量或标识符是哪种类型。 Python提供了内置的type函数,以便确定给定的标识符类型。 我们只需要向type函数提供标识符即可。

识别类型 (Identify Type)

We will provide our identifier or variable like below and type function will return related type.

我们将提供如下所示的标识符或变量,并且type函数将返回相关的类型。

name="ismail" 
type(name) 
#<class 'str'>

We can see that name is a string object or class type

我们可以看到name是一个字符串对象或类类型

检查类型(Check Type)

We can check type returned types with is keyword. We will first provide type function and its parameter identifier or variable and than put is and as the latest type we want to check. In this example we will check if given identifier is string. This will return a boolean result like True or False .

我们可以使用is关键字检查type返回的类型。 首先,我们将提供type的功能和它的参数标识符或变量,不是把is和最新型的,我们要检查。 在此示例中,我们将检查给定的标识符是否为字符串。 这将返回布尔结果,如TrueFalse

name="ismail" 
type(name) is str 
#True

是清单 (Is List)

We can check whether given identifier or variable is a list like below.

我们可以检查给定的标识符或变量是否是如下所示的列表。

mylist=['test'] 
type(mylist) is list 
#True

是字典 (Is Dictionary)

We can check whether given identifier or variable is a dictionary like below.

我们可以检查给定的标识符或变量是否像下面的字典。

mydict={'a':'b','c':'d'} 
type(mydict) is dict 
#True

是字符串 (Is String)

We can check whether given identifier or variable is a string like below.

我们可以检查给定的标识符或变量是否为字符串,如下所示。

name="ismail"  
type(name) is str 
#True

是整数 (Is Integer)

We can check whether given identifier or variable is a integer like below.

我们可以检查给定的标识符或变量是否为整数,如下所示。

mynum=1 
type(mynum) is int 
#True

是对象 (Is Object)

We can check whether given identifier or variable is a object like below.

我们可以检查给定的标识符或变量是否是如下所示的对象。

type(mynum) is object 
#False
LEARN MORE  In Python Operator Usage Tutorial with Examples
在示例中进一步了解Python运算符用法教程

翻译自: https://www.poftut.com/python-type-function-examples/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值