溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python判斷值是哪種數(shù)據(jù)類型的方法

發(fā)布時(shí)間:2020-07-09 11:24:50 來源:億速云 閱讀:161 作者:清晨 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)python判斷值是哪種數(shù)據(jù)類型的方法,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

python判斷值的類型的方法是:1、利用type庫結(jié)合python內(nèi)置的type函數(shù)判斷值的數(shù)據(jù)類型;2、使用python內(nèi)置函數(shù)isinstance判斷值的數(shù)據(jù)類型。

python判斷值是哪種數(shù)據(jù)類型的方法

import types 
type(x) is types.IntType # 判斷是否int 類型 
type(x) is types.StringType #是否string類型

超級(jí)惡心的模式,不用記住types.StringType

import types 
type(x) == types(1) # 判斷是否int 類型 
type(x) == type('a') #是否string類型

使用內(nèi)嵌函數(shù):

isinstance ( object, classinfo )

Return true if the object argument is an instance of the classinfo argument, or of a (direct or indirect) subclass thereof. Also return true if classinfo is a type object and object is an object of that type. If object is not a class instance or an object of the given type, the function always returns false. If classinfo is neither a class object nor a type object, it may be a tuple of class or type objects, or may recursively contain other such tuples (other sequence types are not accepted). If classinfo is not a class, type, or tuple of classes, types, and such tuples, a TypeError exception is raised. Changed in version 2.2: Support for a tuple of type information was added.
Python可以得到一個(gè)對(duì)象的類型 ,利用type函數(shù):

>>>lst = [1, 2, 3]
>>>type(lst)
<type 'list'>

不僅如此,還可以利用isinstance函數(shù),來判斷一個(gè)對(duì)象是否是一個(gè)已知的類型。

isinstance說明如下:

isinstance(object, class-or-type-or-tuple) -> bool

Return whether an object is an instance of a class or of a subclass thereof.
With a type as second argument, return whether that is the object's type.
The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for 
isinstance(x, A) or isinstance(x, B) or ... (etc.).

其第一個(gè)參數(shù)為對(duì)象,第二個(gè)為類型名或類型名的一個(gè)列表。其返回值為布爾型。若對(duì)象的類型與參數(shù)二的類型相同則返回True。若參數(shù)二為一個(gè)元組,則若對(duì)象類型與元組中類型名之一相同即返回True。

>>>isinstance(lst, list)
Trueisinstance(lst, (int, str, list))
True
>>>isinstance(lst, (int, str, list))
True

關(guān)于python判斷值是哪種數(shù)據(jù)類型的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI