1. 程式人生 > >python type函式和isintance函式 獲取資料的資料型別

python type函式和isintance函式 獲取資料的資料型別

引言

  • 有時候可能需要確定一個變數的資料型別, 例如使用者的輸入, 當需要使用者輸入一個整數, 但使用者卻輸入一個字串,就有可能引發一些意想不到的錯誤或者導致程式崩潰.

  • 簡言之, 就是程式設計過程中, 有時是需要確定變數的資料型別的, 不然可能會導致錯誤

獲取資料型別

  • python 可以通過type()函式來獲取變數的資料型別

如:

>>> type(666) # 整數型別
<class 'int'>

>>> type('666') # 字串型別
<class 'str'>

>>> type
(66.666) # 浮點數型別 <class 'float'> >>> type(True) # 布林型別 <class 'bool'> >>> type([66,66,66,666]) # 列表型別 <class 'list'> >>> type((66,66,666,666)) # 元組型別 <class 'tuple'> >>> type(range(5)) # range型別 <class 'range'>

判斷變數資料型別是否相等

  • 方法一, 使用isinstance()函式 (推薦
    )

isintance()函式有兩個引數, 第一個引數是待確定型別的資料, 第二個引數是指定一個數據型別, 若第一個引數的資料型別同第二個引數指定的資料型別, 返回 True, 否則返回False

>>> print(isinstance(6666, int))
True
>>> print(isinstance(6666, float))
False
>>> print(isinstance(6666., float))
True
>>> print(isinstance('6666', str))
True
  • 方法二, 使用type()函式
>>> a = 6666
>>> b = '6666'
>>> if type(a) == type(b):
...     print('Type of a and type of b is the same')
... else:
...     print('Not the same')
... 
Not the same
>>>