LoginSignup
10
7

More than 1 year has passed since last update.

【Python】文字列の数字をint()で数値に変換する時、引数に空文字やNoneが入ってきた場合エラーを回避する方法

Last updated at Posted at 2023-01-18

背景

可変で流れてくる文字列の数値をint()で数値に変換して変数に格納するという処理をコーディングしていた。
この文字列の部分が稀に空文字で流れてくることもあり、その場合int()でエラーが発生してしまうことがわかったのでエラーの回避方法があるか調査してみた。

この記事を読むとできるようになること

int()で引数に空文字やNoneが渡された場合、エラーを回避してデフォルト値を返却できるようになる。

まずは調べてみた

ググった結果、知りたかったことが書いてるサイトを発見!!
こちらの記事を参考に、実際に試してみる。

記事を元に試してみる

int()に空文字やNoneを渡して実行してみる

>>> print(int('1'))
1

>>> print(int(''))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

>>> print(int(None))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

普通にやったら、文字列の数字は変換できるけど空文字やNoneが来るとエラーになる。

int()にorとデフォルト値を設定して実行してみる

>>> print(int('1' or 0))
1
>>> print(int('' or 0))
0
>>> print(int(None or 0))
0

orとその後にデフォルト値として返却したい整数を指定することで
空文字やNoneが引数に渡されてもエラーになることなく指定したデフォルト値が変えるようになった!

ちなみにorの左辺右辺の値を空文字にしてみるとエラーになる。

>>> print(int('' or ''))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

どうやらこんな動きをしてそう。

  1. orの左辺の値をチェックしてTrueならその値をint()で変換、Falseなら右辺の値を確認する。
  2. 左辺がFalse判定されたら右辺も同じように確認して、Trueなら右辺の値をint()で変換、Falseならエラーを返却。

まとめ

int()で文字列の数字を数値へ変換する時に、引数に空文字やNoneが入ってくるような処理を
書いてた場合、orを活用してエラーを回避できる仕組みを考えて対処する。

10
7
2

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
  3. You can use dark theme
What you can do with signing up
10
7