Python 文字列に特定の部分文字列が含まれているか判定する
Python では、次のものを使用できますinキーワードを使用して、文字列に特定の部分文字列が含まれているかどうかを判定します。この方法は非常に簡単で直感的です。
例
# 文字列を定義する
main_string = "Hello, welcome to the world of Python programming."
# 検索する部分文字列を定義する
sub_string = "Python"
# in キーワードを使用して、部分文字列がメイン文字列に存在するかどうかを判定する
if sub_string in main_string:
print(f"'{sub_string}' is found in the main string.")
else:
print(f"'{sub_string}' is not found in the main string.")
main_string = "Hello, welcome to the world of Python programming."
# 検索する部分文字列を定義する
sub_string = "Python"
# in キーワードを使用して、部分文字列がメイン文字列に存在するかどうかを判定する
if sub_string in main_string:
print(f"'{sub_string}' is found in the main string.")
else:
print(f"'{sub_string}' is not found in the main string.")
コードの説明:
main_stringは、チェックする必要があるメイン文字列です。sub_stringは、検索する部分文字列です。- 使用する
inキーワードを使用して判定しますsub_stringに存在するかどうかmain_string中。存在する場合は、返されますTrue、それ以外の場合は返されますFalse。 - 判定結果に基づいて、対応する情報を出力します。
出力結果:
'Python' is found in the main string.その他の拡張
Python3 例