Pythonのint, floatの使い方: オブジェクトの数値変換
- 作成日: 2021-06-10
- 更新日: 2023-12-24
- カテゴリ: Python
Pythonのint, floatの使い方
Pythonにはintとfloatという関数があります。
これらの関数を使うと文字列などのオブジェクトを数値に変換することが可能です。
結論から言うとint()
とfloat()
を使った数値変換は↓のようにやります。
n = int('1')
print(n)
# 1
n = float('3.14')
print(n)
# 3.14
この記事では具体的に↓を見ていきます。
- int()でオブジェクトを整数に変換
- float()でオブジェクトを実数に変換
int()でオブジェクトを整数に変換
int()
について最初に見てみます。
int()の構造
int()
は↓のような構造を持っています。
class int(x, base=10)
int()
は組み込み関数に分類されてますが、その実体はクラスです。
第1引数のx
には数値、文字列, bytes
, bytearray
のいずれかのオブジェクトを指定できます。
第2引数のbase
が与えられた場合、これらはbase
を基数にした整数リテラルで表されたものである必要があります。
int()
は第1引数x
を変換できなかった場合は例外ValueError
を送出します。
int()を単体で呼び出し
int()
を単体で呼び出すと0
を得ることができます。
n = int()
print(n)
# 0
int()で実数を整数に変換
int()
で浮動小数点数を整数に変換するには↓のようにコードを書きます。
n = int(3.14)
print(n)
# 3
int()で文字列を数値に変換
int()
で文字列を数値に変換するには↓のようにコードを書きます。
n = int('1')
print(n)
# 1
n = int(' -123 ')
print(n)
# -123
int()でバイト列を数値に変換
int()
でバイト列を数値に変換するには↓のようにコードを書きます。
n = int(b'12')
print(n)
# 12
int()でbytearrayを数値に変換
int()
でbytearray
を数値に変換するには↓のようにコードを書きます。
arr = bytearray(b'123')
n = int(arr)
print(n)
# 123
int()の例外補足
int()
は第1引数を数値に変換できなかった場合はValueError
を送出します。
この例外を補足してリカバリーできるようにしておく必要があります。
try:
int('abc')
except ValueError as e:
print(e)
# invalid literal for int() with base 10: 'abc'
また、第1引数が未対応のタイプだった場合は例外TypeError
を送出します。
try:
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()
について見てみます。
float()の構造
float()
は↓のような構造になっています。
class float([x])
float()
は第1引数のx
を浮動小数点数に変換します。
x
は数値、文字列、バイト列、bytearray
のいずれかになります。
この第1引数x
のフォーマットを表すBNF
(文法)は↓のようなものです。
sign ::= "+" | "-"
infinity ::= "Infinity" | "inf"
nan ::= "nan"
numeric_value ::= floatnumber | infinity | nan
numeric_string ::= [sign] numeric_value
↑の場合numeric_string
が引数x
です。
これは0
個以上のsign
とnumeric_value
で構成されます。
sign
は+
か-
のどちらかです。
numeric_value
は実数か、Infinity
, inf
, nan
のいずれかになります。
Infinity
などは大文字(INFINITY
など)でもOKです。
引数x
が浮動小数点数の範囲外であれば例外OverflowError
が送出されます。
float()を単体で呼び出し
float()
を単体で呼び出すと0.0
が得られます。
n = float()
print(n)
# 0.0
float()で整数を実数に変換
float()
に整数を渡すと浮動小数点数に変換できます。
n = float(123)
print(n)
# 123.0
float()で文字列を実数に変換
float()
で文字列を実数に変換するには↓のようにコードを書きます。
n = float('3.14')
print(n)
# 3.14
n = float(' -1.23 ')
print(n)
# -1.23
float()でバイト列を実数に変換
float()
でバイト列を浮動小数点数に変換するには↓のようにコードを書きます。
n = float(b'3.14')
print(n)
# 3.14
float()でbytearrayを実数に変換
float()
でbytearray
を浮動小数点数に変換するには↓のようにコードを書きます。
arr = bytearray(b'3.14')
n = float(arr)
print(n)
# 3.14
Infinity, nanなど
Infinity
やnan
などは↓のように変換されます。
print(float('infinity')) # inf
print(float('INFINITY')) # inf
print(float('inf')) # inf
print(float('INF')) # inf
print(float('nan')) # nan
print(float('NAN')) # nan
print(float('+infinity')) # inf
print(float('-INFINITY')) # -inf
float()の例外補足
float()
は第1引数を数値に変換できなかった場合はint()
と同様にValueError
を送出します。
try:
float('abc')
except ValueError as e:
print(e)
# could not convert string to float: 'abc'
また、第1引数が未対応のタイプだった場合は例外TypeError
を送出します。
try:
float(None)
except TypeError as e:
print(e)
# float() argument must be a string or a number, not 'NoneType'
巨大な整数を渡した場合などは例外OverflowError
が送出されます。
try:
float(2 ** 10000)
except OverflowError as e:
print(e)
# int too large to convert to float
おわりに
今回はPythonのint()
とfloat()
について見てみました。
これらは組み込み関数なので使いたい時にすぐ使えますね。
🦝 < 整数と実数を扱う者よ・・・
🐭 < はい・・・
🦊 < 特にオチはないのか・・・