Python で文字列が数字のみを含むかどうかをチェックする方法

PythonPythonBeginner
今すぐ練習

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、Python で文字列が数字のみで構成されているかどうかをチェックする方法を学びます。この実験では数字のみの文字列について調べ、Python の組み込み関数である isdigit() メソッドを紹介します。このメソッドは、文字列内のすべての文字が数字 (0 - 9) であるかどうかを判断します。

digit_strings.py という Python ファイルを作成し、isdigit() メソッドを使用して、数字のみの文字列と数字以外の文字を含む文字列のテストを行います。異なる文字列の例を使ってスクリプトを実行することで、True または False の出力を確認し、Python で数字のみの文字列を効果的に識別する方法を学びます。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/ControlFlowGroup -.-> python/for_loops("For Loops") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") subgraph Lab Skills python/strings -.-> lab-559568{{"Python で文字列が数字のみを含むかどうかをチェックする方法"}} python/conditional_statements -.-> lab-559568{{"Python で文字列が数字のみを含むかどうかをチェックする方法"}} python/for_loops -.-> lab-559568{{"Python で文字列が数字のみを含むかどうかをチェックする方法"}} python/build_in_functions -.-> lab-559568{{"Python で文字列が数字のみを含むかどうかをチェックする方法"}} end

数字のみの文字列を探索する

このステップでは、Python の数字のみの文字列について学び、それらを識別する方法を学びます。数字のみの文字列とは、数字の文字 (0 - 9) のみを含む文字列のことです。Python は、文字列が数字のみで構成されているかどうかを簡単にチェックできる組み込みメソッド isdigit() を提供しています。

まず、VS Code エディタを使用して、~/project ディレクトリに digit_strings.py という名前の Python ファイルを作成しましょう。

## Create a string containing only digits
digit_string = "12345"

## Use the isdigit() method to check if the string contains only digits
is_digit = digit_string.isdigit()

## Print the result
print(is_digit)

ファイルを保存します。次に、python コマンドを使用してスクリプトを実行しましょう。

python ~/project/digit_strings.py

以下の出力が表示されるはずです。

True

これは、文字列 digit_string が数字のみを含んでいることを示しています。

次に、数字以外の文字を含む文字列を試してみましょう。

## Create a string containing digits and letters
non_digit_string = "123abc"

## Use the isdigit() method to check if the string contains only digits
is_digit = non_digit_string.isdigit()

## Print the result
print(is_digit)

digit_strings.py の内容を上記のコードに置き換えて保存します。再度スクリプトを実行しましょう。

python ~/project/digit_strings.py

以下の出力が表示されるはずです。

False

これは、文字列 non_digit_string が数字以外の文字を含んでいることを示しています。

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 を返します。

数字以外の文字のチェック

このステップでは、文字列に数字以外の文字が含まれているかどうかを識別する方法を学びます。isdigit() メソッドは、文字列の すべての 文字が数字であるかどうかをチェックするのに便利ですが、時には少なくとも 1 つの数字以外の文字が存在するかどうかを知る必要があります。

これは、文字列を繰り返し処理し、各文字を個別にチェックすることで実現できます。~/project ディレクトリ内の digit_strings.py ファイルを修正してこれを実装しましょう。

def has_non_digit(input_string):
  """
  Checks if a string contains any non-digit characters.
  """
  for char in input_string:
    if not char.isdigit():
      return True  ## Found a non-digit character
  return False  ## No non-digit characters found


## Test cases
string1 = "12345"
string2 = "123abc"
string3 = "  123"

print(f"'{string1}' has non-digit characters: {has_non_digit(string1)}")
print(f"'{string2}' has non-digit characters: {has_non_digit(string2)}")
print(f"'{string3}' has non-digit characters: {has_non_digit(string3)}")

digit_strings.py の内容を上記のコードに置き換えて保存します。次に、python コマンドを使用してスクリプトを実行しましょう。

python ~/project/digit_strings.py

以下の出力が表示されるはずです。

'12345' has non-digit characters: False
'123abc' has non-digit characters: True
'  123' has non-digit characters: True

このスクリプトでは、入力文字列の各文字を繰り返し処理する has_non_digit() 関数を定義しています。not char.isdigit() を使用して数字でない文字を見つけると、直ちに True を返します。ループが完了しても数字以外の文字が見つからない場合は、False を返します。

このアプローチを使用すると、文字列に数字以外の文字が含まれているかどうかをすばやく判断でき、データ検証やその他のタスクに役立ちます。

まとめ

この実験では、Python で文字列が数字のみを含むかどうかをチェックする方法を学びました。数字のみの文字列は数値文字 (0 - 9) のみで構成され、Python では簡単に識別できる組み込みの isdigit() メソッドが用意されていることを学びました。

数字のみを含む文字列で isdigit() メソッドを使用すると True が返され、数字以外の文字を含む文字列では False が返されることを実践しました。これにより、このメソッドが文字列を検証し、それが完全に数字で構成されているかどうかを判断する能力が実証されました。