startswith() メソッドを使用する
このステップでは、startswith() メソッドをさらに深く掘り下げ、さまざまな引数を使った機能を探ります。文字列内の特定の位置で接頭辞をチェックする方法や、複数の接頭辞をチェックする方法を学びます。
startswith() メソッドは、接頭辞のチェックを行う開始位置と終了位置を指定するためのオプション引数を受け取ることができます。構文は以下の通りです。
string.startswith(prefix, start, end)
prefix: チェックする接頭辞。
start: チェックの開始位置(オプション)。
end: チェックの終了位置(オプション)。
これらの機能を実証するために、prefix_example.py ファイルを変更しましょう。
-
VS Code エディタで prefix_example.py ファイルを開きます。
-
コードを以下のように変更します。
message = "Hello, LabEx!"
## Check if the string starts with "Hello"
if message.startswith("Hello"):
print("The string starts with 'Hello'")
else:
print("The string does not start with 'Hello'")
## Check if the string starts with "LabEx" starting from position 7
if message.startswith("LabEx", 7):
print("The string starts with 'LabEx' at position 7")
else:
print("The string does not start with 'LabEx' at position 7")
## Check if the string starts with "Hello" within the first 5 characters
if message.startswith("Hello", 0, 5):
print("The string starts with 'Hello' within the first 5 characters")
else:
print("The string does not start with 'Hello' within the first 5 characters")
このコードでは、startswith() メソッドに start と end の引数を使った 2 つのチェックを追加しています。最初のチェックは、文字列が位置 7 から "LabEx" で始まるかどうかを確認します。2 番目のチェックは、文字列の最初の 5 文字以内で "Hello" で始まるかどうかを確認します。
-
prefix_example.py ファイルを保存します。
-
ターミナルで python コマンドを使ってスクリプトを実行します。
python ~/project/prefix_example.py
以下の出力が表示されるはずです。
The string starts with 'Hello'
The string starts with 'LabEx' at position 7
The string does not start with 'Hello' within the first 5 characters
この出力は、start と end の引数を使って、文字列内の特定の位置で接頭辞をチェックできることを示しています。
次に、タプルを使って複数の接頭辞をチェックする方法を探りましょう。
-
prefix_example.py ファイルを以下のように変更します。
message = "Hello, LabEx!"
## Check if the string starts with "Hello" or "Hi"
if message.startswith(("Hello", "Hi")):
print("The string starts with 'Hello' or 'Hi'")
else:
print("The string does not start with 'Hello' or 'Hi'")
## Check if the string starts with "Goodbye" or "Welcome"
if message.startswith(("Goodbye", "Welcome")):
print("The string starts with 'Goodbye' or 'Welcome'")
else:
print("The string does not start with 'Goodbye' or 'Welcome'")
このコードでは、接頭辞のタプルを使った 2 つのチェックを追加しています。最初のチェックは、文字列が "Hello" または "Hi" で始まるかどうかを確認します。2 番目のチェックは、文字列が "Goodbye" または "Welcome" で始まるかどうかを確認します。
-
prefix_example.py ファイルを保存します。
-
ターミナルで python コマンドを使ってスクリプトを実行します。
python ~/project/prefix_example.py
以下の出力が表示されるはずです。
The string starts with 'Hello' or 'Hi'
The string does not start with 'Goodbye' or 'Welcome'
この出力は、startswith() メソッドでタプルを使って複数の接頭辞をチェックする方法を示しています。