Python で文字列が特定の長さであるかどうかを確認する方法

PythonPythonBeginner
今すぐ練習

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

はじめに

この実験では、Python で文字列が特定の長さを持っているかどうかを確認する方法を学びます。これには、文字列の長さを理解し、空白や特殊文字を含む文字列の文字数を判断するために len() 関数を利用することが含まれます。

まず、事前に定義された文字列の長さを求める 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-559572{{"Python で文字列が特定の長さであるかどうかを確認する方法"}} python/conditional_statements -.-> lab-559572{{"Python で文字列が特定の長さであるかどうかを確認する方法"}} python/for_loops -.-> lab-559572{{"Python で文字列が特定の長さであるかどうかを確認する方法"}} python/build_in_functions -.-> lab-559572{{"Python で文字列が特定の長さであるかどうかを確認する方法"}} end

文字列の長さを理解する

このステップでは、Python で文字列の長さを判断する方法を学びます。文字列の長さを理解することは、テキストデータを効果的に操作および処理できるため、プログラミングにおける基本的な概念です。

Python では、文字列の長さを求めるために len() 関数が使用されます。文字列の長さは、空白や特殊文字を含む、その文字列に含まれる文字の数です。

簡単な例から始めましょう。VS Code エディタを使用して、~/project ディレクトリに string_length.py という名前の新しいファイルを作成します。

## filename: string_length.py
string1 = "Hello, LabEx!"
length1 = len(string1)
print("The length of the string 'Hello, LabEx!' is:", length1)

string2 = "This is a longer string."
length2 = len(string2)
print("The length of the string 'This is a longer string.' is:", length2)

string3 = ""  ## Empty string
length3 = len(string3)
print("The length of the empty string is:", length3)

ファイルを保存し、次にターミナルで以下のコマンドを使用してスクリプトを実行します。

python ~/project/string_length.py

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

The length of the string 'Hello, LabEx!' is: 13
The length of the string 'This is a longer string.' is: 24
The length of the empty string is: 0

ご覧の通り、len() 関数は各文字列の文字数を返します。空の文字列の長さは 0 です。

次に、ユーザー入力を使用した別の例を試してみましょう。string_length.py ファイルを以下のように変更します。

## filename: string_length.py
user_string = input("Enter a string: ")
length = len(user_string)
print("The length of the string you entered is:", length)

ファイルを保存し、再度実行します。

python ~/project/string_length.py

スクリプトは、文字列を入力するように促します。任意の文字列を入力し、Enter キーを押します。例えば:

Enter a string: Python is fun!

出力は以下のようになります。

The length of the string you entered is: 14

これは、len() 関数を使用してユーザーが提供した文字列の長さを判断できることを示しています。

len() 関数の使用

このステップでは、len() 関数をさまざまなシナリオに適用することで、その理解を深めます。様々なデータ型での使用方法を学び、特殊文字や空白文字に対する動作を調べます。

まず、len() が特殊文字や空白文字を含む文字列をどのように扱うかを見てみましょう。~/project ディレクトリ内の string_length.py ファイルを以下の内容に変更します。

## filename: string_length.py
string1 = "  Hello, LabEx!  "  ## String with leading and trailing spaces
length1 = len(string1)
print("The length of the string with spaces is:", length1)

string2 = "你好,LabEx!"  ## String with Unicode characters
length2 = len(string2)
print("The length of the string with Unicode characters is:", length2)

string3 = "Line1\nLine2"  ## String with a newline character
length3 = len(string3)
print("The length of the string with a newline is:", length3)

ファイルを保存して実行します。

python ~/project/string_length.py

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

The length of the string with spaces is: 17
The length of the string with Unicode characters is: 9
The length of the string with a newline is: 11

string1 の先頭と末尾の空白文字は長さに含まれることに注意してください。また、string2 の Unicode 文字はそれぞれ 1 文字としてカウントされます。string3 の改行文字 \n も 1 文字としてカウントされます。

次に、len() を他の文字列メソッドと組み合わせて使用する方法を調べましょう。たとえば、空白文字を削除した後の文字列が空かどうかを確認するために使用できます。string_length.py ファイルを以下のように変更します。

## filename: string_length.py
user_string = input("Enter a string: ")
stripped_string = user_string.strip()  ## Remove leading/trailing whitespace
length = len(stripped_string)

if length == 0:
    print("The string is empty after removing whitespace.")
else:
    print("The length of the string after removing whitespace is:", length)

ファイルを保存して実行します。

python ~/project/string_length.py

先頭と末尾に空白文字を含む文字列を入力します。

Enter a string:   Hello

出力は以下のようになります。

The length of the string after removing whitespace is: 5

空白文字のみを入力した場合、出力は以下のようになります。

Enter a string:
The string is empty after removing whitespace.

この例は、len() 関数と strip() メソッドを組み合わせて、より複雑な文字列操作を行う方法を示しています。strip() メソッドは、文字列の先頭と末尾の空白文字を削除します。

目標の長さと比較する

このステップでは、文字列の長さを目標の長さと比較する方法を学びます。これは、ユーザー入力の検証や特定の長さ要件に合わせなければならないデータの処理など、プログラミングにおける一般的なタスクです。

ユーザーが入力したユーザー名が 3 文字以上 10 文字以下であることを確認したいシナリオを作成しましょう。~/project ディレクトリ内の string_length.py ファイルを以下の内容に変更します。

## filename: string_length.py
username = input("Enter a username: ")
length = len(username)

if length < 3:
    print("Username must be at least 3 characters long.")
elif length > 10:
    print("Username must be no more than 10 characters long.")
else:
    print("Username is valid.")

ファイルを保存して実行します。

python ~/project/string_length.py

ユーザー名が短すぎる場合:

Enter a username: ab

出力は以下のようになります。

Username must be at least 3 characters long.

ユーザー名が長すぎる場合:

Enter a username: abcdefghijk

出力は以下のようになります。

Username must be no more than 10 characters long.

有効なユーザー名を入力した場合:

Enter a username: abcdef

出力は以下のようになります。

Username is valid.

この例は、len() 関数を使用して文字列が特定の長さ条件を満たしているかどうかを確認する方法を示しています。

次に、パスワードを検証するより複雑なシナリオを考えてみましょう。パスワードは 8 文字以上 16 文字以下で、少なくとも 1 つの数字を含まなければなりません。string_length.py ファイルを以下のように変更します。

## filename: string_length.py
password = input("Enter a password: ")
length = len(password)

has_digit = False
for char in password:
    if char.isdigit():
        has_digit = True
        break

if length < 8:
    print("Password must be at least 8 characters long.")
elif length > 16:
    print("Password must be no more than 16 characters long.")
elif not has_digit:
    print("Password must contain at least one digit.")
else:
    print("Password is valid.")

ファイルを保存して実行します。

python ~/project/string_length.py

パスワードが短すぎる場合:

Enter a password: abcdefg

出力は以下のようになります。

Password must be at least 8 characters long.

パスワードが長すぎる場合:

Enter a password: abcdefghijklmnopq

出力は以下のようになります。

Password must be no more than 16 characters long.

パスワードに数字が含まれていない場合:

Enter a password: abcdefgh

出力は以下のようになります。

Password must contain at least one digit.

有効なパスワードを入力した場合:

Enter a password: abcdefg1

出力は以下のようになります。

Password is valid.

この例は、len() 関数を他の手法(文字列内をループして特定の文字をチェックするなど)と組み合わせて、より高度な検証を行う方法を示しています。

まとめ

この実験では、Python で len() 関数を使用して文字列の長さを求める方法を学びました。この実験では、空文字列を含む事前定義された文字列の長さを計算する方法、およびユーザーから文字列の入力を取得してその長さを計算する方法を示しました。

提供された例では、len() 関数が文字列内の文字数(空白や特殊文字を含む)を返し、空文字列の長さが 0 であることが示されました。また、ターミナルから Python スクリプトを実行し、出力を確認する練習も行いました。