Pythonで数字の文字列strを数値int, floatに変換

Modified: | Tags: Python, 文字列

Pythonで数字の文字列strを数値に変換したい場合、整数に変換するにはint()、浮動小数点数に変換するにはfloat()を使う。

なお、数値を文字列に変換する場合はstr()を使えばよい。

数値や文字列を0埋めや2進数、8進数、16進数、指数表記など様々な書式に変換したい場合はformat()関数または文字列メソッドstr.format()を使う。以下の記事を参照。

また、文字列のリストを数値のリストに変換することもできる。以下の記事を参照。

数字の文字列を整数に変換: int()

int()で数字の文字列を整数int型の数値に変換できる。

print(int('100'))
print(type(int('100')))
# 100
# <class 'int'>

.を含む小数、,で桁区切りされた文字列はエラーValueErrorとなる。

# print(int('1.23'))
# ValueError: invalid literal for int() with base 10: '1.23'

# print(int('10,000'))
# ValueError: invalid literal for int() with base 10: '10,000'

カンマ区切りされた文字列はreplace()メソッドで,を削除(空文字列''に置換)すれば変換可能。

print(int('10,000'.replace(',', '')))
# 10000

replace()については以下の記事を参照。

2022年9月7日以降に公開されたバージョン(Python 3.11, 3.10.7, 3.9.14, 3.8.14, 3.7.14以降)では、整数と文字列の変換がデフォルトで4300桁までに制限されるようになった。詳細は後述。

数字の文字列を浮動小数点数に変換: float()

float()で数字の文字列を浮動小数点数float型の数値に変換できる。

print(float('1.23'))
print(type(float('1.23')))
# 1.23
# <class 'float'>

整数部が省略された文字列は整数部に0が補完されて変換される。

print(float('.23'))
# 0.23

整数の文字列も浮動小数点数float型の数値に変換される。

print(float('100'))
print(type(float('100')))
# 100.0
# <class 'float'>

2進数、8進数、16進数表記の文字列を数値に変換

int()の第二引数に基数を指定すると、文字列を2進数、8進数、16進数などとみなして整数intに変換できる。

print(int('100', 2))
print(int('100', 8))
print(int('100', 16))
# 4
# 64
# 256

これまでの例のように、省略した場合は10進数とみなされる。

print(int('100', 10))
print(int('100'))
# 100
# 100

基数を0とすると、文字列のプレフィックス(0b, 0o, 0xまたは0B, 0O, 0X)をもとに変換される。

print(int('0b100', 0))
print(int('0o100', 0))
print(int('0x100', 0))
# 4
# 64
# 256

プレフィックスや16進数のアルファベットは大文字でも小文字でもどちらでもよい。

print(int('FF', 16))
print(int('ff', 16))
# 255
# 255

print(int('0xFF', 0))
print(int('0XFF', 0))
print(int('0xff', 0))
print(int('0Xff', 0))
# 255
# 255
# 255
# 255

2進数、8進数、16進数の数値・文字列の相互変換については、以下の記事を参照。

指数表記の文字列を数値に変換

指数表記の文字列はfloat()でそのままfloat型に変換できる。

print(float('1.23e-4'))
print(type(float('1.23e-4')))
# 0.000123
# <class 'float'>

print(float('1.23e4'))
print(type(float('1.23e4')))
# 12300.0
# <class 'float'>

eは大文字のEでもよい。

print(float('1.23E-4'))
# 0.000123

全角アラビア数字の文字列を数値に変換

全角のアラビア数字はint()float()でそのまま数値に変換できる。

print(int('100'))
print(type(int('100')))
# 100
# <class 'int'>

print(float('100'))
print(type(float('100')))
# 100.0
# <class 'float'>

ただし、マイナス-や小数点のピリオドなどの記号が全角だとエラーValueErrorになる。

# print(float('ー1.23'))
# ValueError: could not convert string to float: '1.23'

数字が全角でマイナス-、小数点のピリオド.が半角だと問題なく変換できる。replace()メソッドで全角の記号を半角の記号に置換すれば変換可能。

print(float('-1.23'))
# -1.23

print(float('ー1.23'.replace('ー', '-').replace('.', '.')))
# -1.23

漢数字の文字列を数値に変換

unicodedataモジュールのunicodedata.numeric()関数を使うとUnicodeの漢数字一文字を浮動小数点数float型の数値に変換できる。

二文字以上だとエラーTypeError、数字ではない文字もエラーValueErrorになる。

import unicodedata

print(unicodedata.numeric('五'))
print(type(unicodedata.numeric('五')))
# 5.0
# <class 'float'>

print(unicodedata.numeric('十'))
# 10.0

print(unicodedata.numeric('参'))
# 3.0

print(unicodedata.numeric('億'))
# 100000000.0

# print(unicodedata.numeric('五十'))
# TypeError: numeric() argument 1 must be a unicode character, not str

# print(unicodedata.numeric('漢'))
# ValueError: not a numeric character

二文字以上の漢数字を数値に変換したい場合、以下の記事で公開されている漢数字の文字列を半角アラビア数字の文字列に変換するコードが便利。

取得できた半角アラビア数字をint()float()で数値に変換すればよい。

整数・文字列変換の桁数制限

2022年9月7日以降に公開されたバージョン(Python 3.11, 3.10.7, 3.9.14, 3.8.14, 3.7.14以降)では、整数と文字列の変換がデフォルトで4300桁までに制限されるようになった。

整数・文字列変換アルゴリズムがO(n^2)であることを利用したDoS攻撃を防ぐのが目的。

int()str()などの整数・文字列変換で、4300桁より大きい値はValueErrorとなる。

i = int('1' * 5)
print(i)
# 11111

i = int('1' * 4300)

# i = int('1' * 4301)
# ValueError: Exceeds the limit (4300 digits) for integer string conversion: value has 4301 digits; use sys.set_int_max_str_digits() to increase the limit

s = str(10**5)
print(s)
# 100000

s = str(10**4299)

# s = str(10**4300)
# ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit

print()repr()のように内部で整数を文字列に変換する処理も対象なので注意。

i = 10**10000
# print(i)
# ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit

次に紹介するように、基数が2のべき乗(2進数、8進数、16進数など)の変換は無制限。影響を受ける処理・受けない処理については公式ドキュメントも参照。

2進数、8進数、16進数などの変換は無制限

基数が2のべき乗(2進数、8進数、16進数など)の変換は桁数制限の適用外。例えば、int(string, base)base2, 4, 8, 16, 32の場合や、bin(), oct(), hex()による整数から文字列への変換などは4300桁を超えてもエラーにならない。

i = int('1' * 10000, base=16)

s = hex(10**10000)

制限桁数の設定

sys.set_int_max_str_digits()で制限桁数を指定できる。0にすると無制限になる。

import sys

sys.set_int_max_str_digits(1000)

# i = int('1' * 1001)
# ValueError: Exceeds the limit (1000 digits) for integer string conversion: value has 1001 digits; use sys.set_int_max_str_digits() to increase the limit

sys.set_int_max_str_digits(0)

i = int('1' * 100000)

そのほか、環境変数PYTHONINTMAXSTRDIGITSやコマンドラインオプション-X int_max_str_digitsで設定する方法もある。詳細は公式ドキュメントを参照。

上述のように、この制限は脆弱性対応のためのものなので、特に外部からの入力を受け付けるアプリケーションの場合は内容を十分に理解した上で変更すべき。

関連カテゴリー

関連記事