Python 文字列検索:特定文字の検索方法を徹底解説

Pythonでは、find()メソッドを使って文字列内の特定の文字のインデックスを検索することができます。以下に例を示します。

s = "Hello, World!"
char = "o"
index = s.find(char)
if index != -1:
    print(f"Found '{char}' at index {index}")
else:
    print(f"'{char}' not found")

このコードは、文字列sの中から文字oを検索し、見つかったインデックス位置を出力します。文字が存在しない場合は、「oが見つかりません」と出力されます。

bannerAds