Python 型変換とキャスト: 包括的ガイド
Python 型変換と型キャスト
この記事では、型変換とその用途について学びます。
Pythonの型変換を学ぶ前に、Pythonデータ型についての知識があることが前提です。
型変換
あるデータ型(整数、文字列、浮動小数点など)の値を別のデータ型に変換するプロセスを型変換と呼びます。Pythonには2種類の型変換があります。
- 暗黙的型変換
- 明示的型変換
暗黙的型変換
暗黙的型変換では、Pythonが自動的にあるデータ型を別のデータ型に変換します。このプロセスにはユーザーの関与は不要です。
Pythonがデータ損失を避けるため、下位データ型(整数)を上位データ型(浮動小数点)に昇格させる例を見てみましょう。
例1: 整数から浮動小数点への変換
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
プログラムを実行すると出力は:
datatype of num_int: <class 'int'> datatype of num_flo: <class 'float'> Value of num_new: 124.23 datatype of num_new: <class 'float'>
上記プログラムでは、
- 2つの変数num_intとnum_floを加算し、結果をnum_newに格納。
- 3つのオブジェクトのデータ型をそれぞれ確認。
- 出力から、num_intは
integer、num_floはfloat。 - num_newは
float型になる。Pythonは常に小さいデータ型を大きいデータ型に変換してデータ損失を防ぐため。
次に、文字列と整数を加算して、Pythonがどう扱うか見てみましょう。
例2: 文字列(上位)と整数(下位)の加算
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str:",type(num_str))
print(num_int+num_str)
実行結果:
Data type of num_int: <class 'int'> Data type of num_str: <class 'str'> Traceback (most recent call last): File "python", line 7, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str'
上記プログラムでは、
- 2変数num_intとnum_strを加算。
- 出力から
TypeErrorが発生。この条件下ではPythonは暗黙的変換できない。 - しかし、Pythonにはこのような状況への解決策があり、明示的変換として知られています。
明示的型変換
明示的型変換では、ユーザーがオブジェクトのデータ型を必要な型に変換します。int()、float()、str()などの定義済み関数を使って明示的型変換を行います。
この種の変換は、ユーザーがオブジェクトのデータ型をキャスト(変更)するため、型キャストとも呼ばれます。
構文:
<required_datatype>(expression)
必要なデータ型の関数を式に代入することで型キャストできます。
例3: 明示的変換による文字列と整数の加算
num_int = 123
num_str = "456"
print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))
num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))
num_sum = num_int + num_str
print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))
実行結果:
Data type of num_int: <class 'int'> Data type of num_str before Type Casting: <class 'str'> Data type of num_str after Type Casting: <class 'int'> Sum of num_int and num_str: 579 Data type of the sum: <class 'int'>
上記プログラムでは、
- num_strとnum_intを加算。
int()関数でnum_strを文字列(上位)から整数(下位)に変換して加算実行。- num_strを整数値に変換後、Pythonは2変数を加算可能に。
- num_sumの値とデータ型は整数に。
覚えておくべきポイント
- 型変換はオブジェクトをあるデータ型から別のデータ型に変換すること。
- 暗黙的型変換はPythonインタプリタが自動実行。
- Pythonは暗黙的型変換でデータ損失を防ぐ。
- 明示的型変換は型キャストとも呼ばれ、ユーザーが定義済み関数でデータ型を変換。
- 型キャストでは、オブジェクトを特定データ型に強制するためデータ損失が生じる可能性あり。
Python
- C#型変換完全ガイド:暗黙・明示的変換、Parse、Convertクラス
- Python キーワードと識別子: 予約語と命名規則をマスター
- Python 文・インデント・コメント: 明確なガイド
- Python 変数・定数・リテラル: 包括的ガイド
- Python データ型マスター: 実践ガイド
- Python I/Oとモジュールインポート完全マスター: 実践ガイド
- Python グローバル・ローカル・非ローカル変数を理解する
- Pythonにおける数値、型変換、数学のマスター
- Pythonディレクトリ・ファイル操作マスター:作成、移動、一覧、リネーム、削除
- Pythonエラーと組み込み例外をマスターする
- Java型キャスト完全ガイド:拡大変換から縮小変換まで