ユーニックス総合研究所

  • home
  • archives
  • python-type-conv

コードでよくわかるPythonの型変換【初心者向け】

  • 作成日: 2022-04-05
  • 更新日: 2023-12-25
  • カテゴリ: Python

すぐわかるPythonの型変換

Pythonではさまざまな型、intstrなどを扱うことができます。
特定の型から別の型に変換することを型変換といいます。

今回はこのPythonの型変換について詳しく見ていきたいと思います。

関連記事

頭が悪い人のPythonのevalの使い方
頭がいい人のPythonのexitの使い方
状態遷移による文字列パースのテクニック【Python】

頭が悪い人のPythonのevalの使い方
頭がいい人のPythonのexitの使い方
状態遷移による文字列パースのテクニック【Python】

intへの型変換

文字列をint型に変換する場合は、↓のようにint()を使います。

n = int("20")  

print(n)  # 20  

あるいは浮動小数点数をint型に変換する場合も同じです。
浮動小数点数の場合は小数点数以下が丸められます。

n = int(3.14)  

print(n)  # 3  

リストや辞書、タプルや集合はintに変換できません。

try:  
    n = int([1, 2, 3])  
except TypeError as e:  
    print(e)  
    # int() argument must be a string, a bytes-like object or a number, not 'list'  

try:  
    n = int({'a': 1})  
except TypeError as e:  
    print(e)  
    # int() argument must be a string, a bytes-like object or a number, not 'dict'  

try:  
    n = int((1, 2))  
except TypeError as e:  
    print(e)  
    # int() argument must be a string, a bytes-like object or a number, not 'tuple'  

try:  
    n = int({1, 2})  
except TypeError as e:  
    print(e)  
    # int() argument must be a string, a bytes-like object or a number, not 'set'  

Noneも変換できません。

try:  
    n = int(None)  
except TypeError as e:  
    print(e)  
    # int() argument must be a string, a bytes-like object or a number, not 'NoneType'  

floatへの型変換

float(浮動小数点数)はintに近い型です。
振る舞いも大体同じです。

intからfloatへの変換、文字列からfloatへの変換は可能です。

n = float(1)  

print(n)  # 1.0  

n = float("3.14")  

print(n)  # 3.14  

リストや辞書、タプルや集合はfloatに変換できません。

try:  
    n = float([1, 2, 3])  
except TypeError as e:  
    print(e)  
    # float() argument must be a string, a bytes-like object or a number, not 'list'  

try:  
    n = float({'a': 1})  
except TypeError as e:  
    print(e)  
    # float() argument must be a string, a bytes-like object or a number, not 'dict'  

try:  
    n = float((1, 2))  
except TypeError as e:  
    print(e)  
    # float() argument must be a string, a bytes-like object or a number, not 'tuple'  

try:  
    n = float({1, 2})  
except TypeError as e:  
    print(e)  
    # float() argument must be a string, a bytes-like object or a number, not 'set'  

try:  
    n = float(None)  
except TypeError as e:  
    print(e)  
    # float() argument must be a string, a bytes-like object or a number, not 'NoneType'  

strへの型変換

str(文字列)にはどの型も変換できます。
またstrに渡されたときの振る舞いはクラスの場合は__str__()メソッドで定義できます。

s = str(1)  
print(s)  # 1  

s = str(3.14)  
print(s)  # 3.14  

s = str([1, 2, 3])  
print(s)  # [1, 2, 3]  

s = str({'a': 1, 'b': 2})  
print(s)  # {'a': 1, 'b': 2}  

s = str((1, 2, 3))  
print(s)  # (1, 2, 3)  

s = str({1, 2, 3})  
print(s)  # {1, 2, 3}  

s = str(None)  
print(s)  # None  

listへの型変換

list(リスト)にはint, float, Noneは変換できません。
文字列、リスト、タプル、辞書、集合は変換できます。

try:  
    l = list(1)  
except TypeError as e:  
    print(e)  # 'int' object is not iterable  

try:  
    l = list(3.14)  
except TypeError as e:  
    print(e)  # 'float' object is not iterable  

try:  
    l = list(None)  
except TypeError as e:  
    print(e)  # 'NoneType' object is not iterable  

l = list("123")  
print(l)  # ['1', '2', '3']  

l = list((1, 2, 3))  
print(l)  # [1, 2, 3]  

l = list({'a': 1, 'b': 2})  
print(l)  # ['a', 'b']  

l = list({1, 2, 3})  
print(l)  # [1, 2, 3]  

tupleへの型変換

tuple(タプル)はリストに似ています。
int, float, Noneは変換できますが、他の型は変換できます。

try:  
    l = tuple(1)  
except TypeError as e:  
    print(e)  # 'int' object is not iterable  

try:  
    l = tuple(3.14)  
except TypeError as e:  
    print(e)  # 'float' object is not iterable  

try:  
    l = tuple(None)  
except TypeError as e:  
    print(e)  # 'NoneType' object is not iterable  

l = tuple("123")  
print(l)  # ('1', '2', '3')  

l = tuple([1, 2, 3])  
print(l)  # (1, 2, 3)  

l = tuple({'a': 1, 'b': 2})  
print(l)  # ('a', 'b')  

l = tuple({1, 2, 3})  
print(l)  # (1, 2, 3)  

dictへの変換

dict(辞書)には全ての型を変換できません。

try:  
    d = dict(1)  
except TypeError as e:  
    print(e)  # 'int' object is not iterable  

try:  
    d = dict(3.14)  
except TypeError as e:  
    print(e)  # 'float' object is not iterable  

try:  
    d = dict(None)  
except TypeError as e:  
    print(e)  # 'NoneType' object is not iterable  

try:  
    d = dict("123")  
except ValueError as e:  
    print(e)  # dictionary update sequence element #0 has length 1; 2 is required  

try:  
    d = dict((1, 2, 3))  
except TypeError as e:  
    print(e)  # cannot convert dictionary update sequence element #0 to a sequence  

try:  
    d = dict({'a': 1, 'b': 2})  
except TypeError as e:  
    print(e)  # cannot convert dictionary update sequence element #0 to a sequence  

try:  
    d = dict({1, 2, 3})  
except TypeError as e:  
    print(e)  # cannot convert dictionary update sequence element #0 to a sequence  

しかし、2つのリストをzipした場合は辞書へ変換できます。

l1 = ['a', 'b']  
l2 = [1, 2]  

d = dict(zip(l1, l2))  
print(d)  # {'a': 1, 'b': 2}  

これはl1が辞書のキーに、l2が辞書の値になっています。
l1がキーとして利用できない場合はエラーになります。

setへの型変換

set(集合)もリストやタプルと似ています。
整数、浮動小数点数、Noneは変換できませんが他はできます。

try:  
    s = set(1)  
except TypeError as e:  
    print(e)  # 'int' object is not iterable  

try:  
    s = set(3.14)  
except TypeError as e:  
    print(e)  # 'float' object is not iterable  

try:  
    s = set(None)  
except TypeError as e:  
    print(e)  # 'NoneType' object is not iterable  

s = set("123")  
print(s)  # {'1', '2', '3'}  

s = set((1, 2, 3))  
print(s)  # {1, 2, 3}  

s = set({'a': 1, 'b': 2})  
print(s)  # {'a', 'b'}  

s = set({1, 2, 3})  
print(s)  # {1, 2, 3}  

おわりに

今回はPythonの型変換を解説しました。
特定の型に型変換できない型もありますので注意が必要です。

🦝 < コンバート

🐭 < コンビナート