Pythonで文字列が数字かどうかを判定

Python3 実例

以下の実例は、カスタム関数を作成してis_number()文字列が数字かどうかを判定する方法:

実例(Python 3.0+)

# -*- coding: UTF-8 -*- # Filename : test.py # author by : www.example.com def is_number(s): try: float(s) return True except ValueError: pass try: import unicodedata unicodedata.numeric(s) return True except (TypeError, ValueError): pass return False # 文字列と数字をテスト print(is_number('foo')) # False print(is_number('1')) # True print(is_number('1.3')) # True print(is_number('-1.37')) # True print(is_number('1e3')) # True # Unicodeをテスト # アラビア語 5 print(is_number('٥')) # True # タイ語 2 print(is_number('๒')) # True # 中国語の数字 print(is_number('四')) # True # 著作権番号 print(is_number('©')) # False

インラインのif文を使用して実装することもできます:

上記のコードを実行した場合の出力結果は次のとおりです:

False
True
True
True
True
True
True
True
False

その他の方法

Python isdigit() この方法は、文字列が数字だけで構成されているかを検出します。

Python isnumeric() この方法は、文字列が数字だけで構成されているかを検出します。この方法はunicodeオブジェクトのみを対象とします。

Python3 実例

その他の拡張