工業製造
産業用モノのインターネット | 工業材料 | 機器のメンテナンスと修理 | 産業プログラミング |
home  MfgRobots >> 工業製造 >  >> Industrial programming >> Python

Python 型変換とキャスト: 包括的ガイド

Python 型変換と型キャスト

この記事では、型変換とその用途について学びます。

Pythonの型変換を学ぶ前に、Pythonデータ型についての知識があることが前提です。


型変換

あるデータ型(整数、文字列、浮動小数点など)の値を別のデータ型に変換するプロセスを型変換と呼びます。Pythonには2種類の型変換があります。

  1. 暗黙的型変換
  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'>

上記プログラムでは、


次に、文字列と整数を加算して、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'

上記プログラムでは、


明示的型変換

明示的型変換では、ユーザーがオブジェクトのデータ型を必要な型に変換します。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'>

上記プログラムでは、


覚えておくべきポイント

  1. 型変換はオブジェクトをあるデータ型から別のデータ型に変換すること。
  2. 暗黙的型変換はPythonインタプリタが自動実行。
  3. Pythonは暗黙的型変換でデータ損失を防ぐ。
  4. 明示的型変換は型キャストとも呼ばれ、ユーザーが定義済み関数でデータ型を変換。
  5. 型キャストでは、オブジェクトを特定データ型に強制するためデータ損失が生じる可能性あり。

Python

  1. C#型変換完全ガイド:暗黙・明示的変換、Parse、Convertクラス
  2. Python キーワードと識別子: 予約語と命名規則をマスター
  3. Python 文・インデント・コメント: 明確なガイド
  4. Python 変数・定数・リテラル: 包括的ガイド
  5. Python データ型マスター: 実践ガイド
  6. Python I/Oとモジュールインポート完全マスター: 実践ガイド
  7. Python グローバル・ローカル・非ローカル変数を理解する
  8. Pythonにおける数値、型変換、数学のマスター
  9. Pythonディレクトリ・ファイル操作マスター:作成、移動、一覧、リネーム、削除
  10. Pythonエラーと組み込み例外をマスターする
  11. Java型キャスト完全ガイド:拡大変換から縮小変換まで