Python:例題付き Python の型キャストと型変換
Python•型変換

例題付き Python の型キャストと型変換

Python には int()、float()、str()、bool()、list()、set() などの明示的な変換コンストラクタがあり、互換性のない型同士を安全に変換できます。

構文

new_value = target_type(original_value)

パラメータと値

この構文の主な構成要素と指定可能な値:

パラメータ型説明
target_typeType constructorint、float、str、bool、list、tuple、または set。
original_valueAny convertible objectキャスト対象の値。

そのまま実行できるコード例

Compilra で実行可能

Python をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:

# Explicit Type Casting in Python
raw_price = "49.95"
quantity_str = "3"

# Convert strings to float and int
unit_price = float(raw_price)
quantity = int(quantity_str)
subtotal = unit_price * quantity

# Boolean truthiness conversion
empty_list = []
active_items = ["Laptop", "Mouse"]

print(f"Unit Price: ${unit_price} ({type(unit_price).__name__})")
print(f"Quantity:   {quantity} ({type(quantity).__name__})")
print(f"Subtotal:   ${subtotal:.2f}")
print(f"Empty list bool:  {bool(empty_list)}")
print(f"Active items bool: {bool(active_items)}")
期待される出力:
Unit Price: $49.95 (float)
Quantity:   3 (int)
Subtotal:   $149.85
Empty list bool:  False
Active items bool: True

動作のしくみ: ステップ解説

  • 6-7 行目: 数値文字列を float と int のプリミティブへ変換します。
  • 8 行目: 浮動小数点数と整数の乗算を正しく実行します。
  • 15-16 行目: Python の真偽評価(truthiness)を示します:空のコンテナは False になります。

重要ポイント

  • float("49.95") はテキストから小数を解析します。
  • int("3") は整数値を抽出します。数字以外の文字列を渡すと ValueError が発生します。
  • bool() は空文字列、0、None、空コレクションを False に変換します。

よくある間違い: 小数点を含む文字列を直接 int() に渡す

int("49.95") は ValueError を送出します。先に float に変換してから int に変換してください。

❌ 誤り
price = int("49.95") # ValueError: invalid literal for int()
✅ 正しい例
price = int(float("49.95")) # Correct: turns 49.95 into 49

関連するPythonチュートリアルとコンパイラ

Compilra で Python を実行・テストする

Compilraのクラウドコンパイラ上で事前設定した標準入力 (stdin) を使ってこのコードを実行できます。