LoginSignup
41

More than 5 years have passed since last update.

posted at

Organization

【Python】int() 関数の注意点

Python では、int() 関数を使って、整数に変換する時に一つ注意点があります。以下の例をご参照ください。

>>> int(100)     #整数ー>整数、OK
100
>>> int(100.0)   #浮動小数点ー>整数、OK
100
>>> int('100')   #文字列(整数)ー>整数、OK
100
>>> int('100.0') #文字列(浮動小数点)ー>エラー
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '100.0'

回避策の一つとしては、以下の例がご参照できます。

>>> int(float('100.0'))
100

尚、float() には、このような問題はありません。

>>> float(100)
100.0
>>> float('100')
100.0
>>> float('100.0')
100.0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
41