isdigit() メソッドの使用
前のステップでは、数字のみの文字列の基本と isdigit()
メソッドの使い方を学びました。このステップでは、isdigit()
メソッドについて詳しく調べ、さまざまな種類の文字列でどのように使用できるかを見ていきます。
isdigit()
メソッドは Python の文字列メソッドで、文字列内のすべての文字が数字である場合に True
を返し、そうでない場合は False
を返します。これは、ユーザー入力の検証や数字のみを含むデータの処理に役立つ、シンプルで強力なツールです。
~/project
ディレクトリ内の digit_strings.py
ファイルを引き続き使用しましょう。スクリプトを修正して、さまざまな文字列で isdigit()
メソッドをテストします。
まず、空の文字列を使ってテストしてみましょう。
## Create an empty string
empty_string = ""
## Use the isdigit() method to check if the string contains only digits
is_digit = empty_string.isdigit()
## Print the result
print(is_digit)
digit_strings.py
の内容を上記のコードに置き換えて保存します。再度スクリプトを実行しましょう。
python ~/project/digit_strings.py
以下の出力が表示されるはずです。
False
空の文字列には数字が含まれていないため、isdigit()
は False
を返します。
次に、空白のみを含む文字列を使ってテストしてみましょう。
## Create a string containing only spaces
space_string = " "
## Use the isdigit() method to check if the string contains only digits
is_digit = space_string.isdigit()
## Print the result
print(is_digit)
digit_strings.py
の内容を上記のコードに置き換えて保存します。再度スクリプトを実行しましょう。
python ~/project/digit_strings.py
以下の出力が表示されるはずです。
False
空白のみを含む文字列は数字のみの文字列とは見なされないため、isdigit()
は False
を返します。
最後に、Unicode 数字を含む文字列を使ってテストしてみましょう。
## Create a string containing Unicode digits
unicode_digit_string = "一二三" ## These are Chinese numerals
## Use the isdigit() method to check if the string contains only digits
is_digit = unicode_digit_string.isdigit()
## Print the result
print(is_digit)
digit_strings.py
の内容を上記のコードに置き換えて保存します。再度スクリプトを実行しましょう。
python ~/project/digit_strings.py
以下の出力が表示されるはずです。
False
isdigit()
メソッドは、ASCII 数字 (0 - 9) に対してのみ True
を返し、数字を表す他の Unicode 文字に対しては False
を返します。