【Python入門】文字列が特定の文字列で始まるかどうかを確認する方法とは?文字列の特定の文字列で始まるかどうかの確認方法を徹底解説

Python

Pythonの「str」とは、文字列を表すデータ型の一つです。文字列とは、文字の並びであり、例えば「hello, world!」や「1234」などが該当します。「str」はイミュータブル(不変)なデータ型であり、一度作成された文字列オブジェクトの内容を変更することはできません。また、「str」は、シングルクォーテーション(‘)、ダブルクォーテーション(“)、トリプルクォーテーション(”’ or “””)のどれかで文字列を定義することができます。文字列に対して、様々な操作を行うことができます。例えば、文字列の結合、分割、検索、置換、フォーマットなどがあります。本記事では、Pythonによる文字列が特定の文字列で始まるかどうかを確認する方法を紹介します。

下記の様な内容で悩んでいる/困っている場合に使える方法を参考までにご共有させて頂きます。

・Pythonの場合、どうやって文字列の状態を確認するの?
・Pythonの文字列は、どの様に特定の文字列で始まるかどうかを確認するのだろうか?

特定の文字列で始まるかどうかの確認(自作関数)

関数の定義

def stringStartsWith(input_str: str, input_substr: str) -> bool:
    return input_str.startswith(input_substr)

使用例1

SampleString = 'AAA'
CheckStringStartsWith = stringStartsWith(SampleString, 'A')
print(f"String Starts With:\n{CheckStringStartsWith} {type(CheckStringStartsWith)}")
String Starts With:
True <class 'bool'>

使用例2

SampleString = 'AAA'
CheckStringStartsWith = stringStartsWith(SampleString, 'AA')
print(f"String Starts With:\n{CheckStringStartsWith} {type(CheckStringStartsWith)}")
String Starts With:
True <class 'bool'>

使用例3

SampleString = 'AAA'
CheckStringStartsWith = stringStartsWith(SampleString, 'a')
print(f"String Starts With:\n{CheckStringStartsWith} {type(CheckStringStartsWith)}")
String Starts With:
False <class 'bool'>

まとめ

Pythonの文字列はPython標準で使えるデータ型であり、Pythonでプログラムする上でよく使うものとなっております。この記事では、Pythonによる文字列が特定の文字列で始まるかどうかを確認する方法を紹介しました。ぜひ活用してみてください。

関連検索ワード

How to check if a string starts with a specific substring?
How to check if a string begins with a specific substring?

関連キーワード

python, 入門, 初心者, 文字列, 始まる, 確認, string, check, start, begin