Pythonでは、文字列内に特定の文字列が存在するかどうかを確認するためのいくつかの方法があります。最も一般的な方法は、in
というメンバーシップ演算子を使用することです。
raw_file_content = "Hi there and welcome. This is a special hidden file with a SECRET secret. I don't want to tell you The Secret, but I do want to secretly tell you that I have one."
"secret" in raw_file_content # True
上記のコードでは、in
演算子を使用してraw_file_content
に"secret"
という文字列が含まれているかどうかを確認しています。
また、複数の文字列が文字列内に存在するかどうかを確認する場合は、any
関数を使用することができます。
a_string = "A string is more than its parts!"
matches = ["more", "wholesome", "milk"]
if any(x in a_string for x in matches):
print("Match found!")
このコードでは、matches
リスト内の任意の文字列がa_string
に存在するかどうかを確認しています。
これらの方法を使用することで、Pythonで文字列内に特定の文字列が存在するかどうかを簡単に確認することができます。これは、ファイルからのテキスト内容の操作やユーザー入力の受け取りなど、様々なシチュエーションで役立つでしょう。