python データの型を取得・判定する

python データの型を取得・判定する

pythonで、type関数を使って、データの型を取得・判定するサンプルコードを記述してます。pythonのバージョンは3.8.5を使用してます。

環境

  • OS windows10 pro 64bit
  • python 3.8.5

type使い方

type関数を使用すれば、データの型を取得することが可能です。

print( type("mebee") )
# <class 'str'>

print( type(100) )
# <class 'int'>

print( type(0.1) )
# <class 'float'>

print( type(True) )
# <class 'bool'>

print( type([1,2,3,4]) )
# <class 'list'>

print( type({"a":1, "b":2, "c":3}) )
# <class 'dict'>

def hoge():
    return(0)

print( type(hoge) )
# <class 'function'>

また、以下のように型を判定することも可能です。

print(type("mebee") is str)
# True

print(type(10) is str)
# False

print(type("mebee") is int)
# False

print(type(10) is int)
# True

in演算子を利用して、複数の型を判定することも可能です。

print(type("mebee") in (str, int))
# True