1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonの文字列の数字判定のdecimal()とisnumeric()が使えないとき

Posted at

数字の判定にはisdigit()、decimal()、isnumeric()

文字列が数字であるかどうかを判定するのによく用いるのがこの3つのメソッド。
しかし、ふとした時にdecimal()とisnumeric()が使えないことに気づく。

因みにこれら3メソッドの違いは、次のような感じ?

isdigit():半角全角数字だけでなく、バイト文字、ローマ数字に対応
isdecimal():半角全角数字だけ対応
isnumeric():半角全角数字だけでなく、バイト文字、ローマ数字、漢数字に対応

対応範囲はisdecimal()<isdigit()<isnumeric()という感じ。

いつでもこれらのメソッドが使えると思っていたら罠

ふとした時に、isdecimal()とisnumeric()でエラーになるところを発見。

In [3]: test = '10'

In [4]: test.isdecimal()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-65eac6932f46> in <module>()
----> 1 test.isdecimal()

AttributeError: 'str' object has no attribute 'isdecimal'

どうやら、こいつらは対象の文字がUTF-8である必要があるとのこと。

対応方法

そもそもshift-JISの場合はどうするのか?というのはあるのだけれど、基本的には以下のようにすれば動作する。

test = '10'
unicode(test).isnumeric()

最後に

値が常にUTF-8で来ることが保証されている環境なら問題ないと思うが、変数を'10'のように宣言しているとこの罠にはまる。
u'10'ならば良い。

この罠を食らったのは、ユニットテストを作っているところだった。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?