文字列メソッド

endswith()

文字列が指定した文字列で終わっているかを判定します。

構文

文字列.endswith(検索文字列)

使用例

print('hello.py'.endswith('.py'))

実行結果

True

💡 実践的な使用例

files = ['photo.jpg', 'report.pdf', 'note.txt']
images = [f for f in files if f.endswith(('.jpg', '.png'))]
print(images)

endswith()にはタプルで複数の候補を渡すこともでき、「.jpgか.pngのどちらかで終わる」といった判定を1行で書けます。

関連トピック

文字列 startswith()

← メソッド辞典に戻る