Pythonで文字列の先頭と末尾が特定の文字列か判定(startswith, endswith)
この記事では、Pythonの文字列メソッドであるstartswith()とendswith()の使い方を解説します。これらのメソッドを使うことで、文字列の先頭または末尾が特定の文字列と一致するかどうかを簡単に判定できます。様々な例題を通して、これらのメソッドの使用方法と応用方法を学びます。
目次
startswith()メソッドの使い方
startswith()メソッドは、文字列が特定の文字列で始まるかどうかを判定します。引数には、判定したい文字列を指定します。一致する場合はTrue、一致しない場合はFalseを返します。
string = "Hello, world!"
print(string.startswith("Hello")) # True
print(string.startswith("World")) # False
print(string.startswith("He")) # True
大文字と小文字を区別します。
string = "Hello, world!"
print(string.startswith("hello")) # False
endswith()メソッドの使い方
endswith()メソッドは、文字列が特定の文字列で終わるかどうかを判定します。引数には、判定したい文字列を指定します。一致する場合はTrue、一致しない場合はFalseを返します。
string = "Hello, world!"
print(string.endswith("! ")) # False
print(string.endswith("!")) # True
print(string.endswith("world!")) # True
startswith()メソッドと同様に、大文字と小文字を区別します。
string = "Hello, world!"
print(string.endswith("WORLD!")) # False
実践例:ファイル名の拡張子判定
startswith()とendswith()は、ファイル名の拡張子判定などにも役立ちます。
filename = "image.jpg"
print(filename.endswith(".jpg")) # True
print(filename.endswith((".jpg", ".png"))) # True
filename2 = "document.pdf"
print(filename2.endswith((".jpg", ".png"))) # False
注意点
startswith()とendswith()メソッドは、大文字と小文字を区別します。大文字と小文字を区別せずに判定したい場合は、文字列を小文字に変換してから使用してください。
string = "Hello, world!"
print(string.lower().startswith("hello")) # True
関連記事
- Pythonで文字列を分割(split, rsplit, splitlines)
- Pythonで文字列を検索(find, rfind, index, rindex)
- Pythonで文字列を中央寄せ・左寄せ・右寄せ(center, ljust, rjust)
- Pythonで文字列を置換(replace, translate, re.sub)
- Pythonで文字列の大文字・小文字を変換(upper, lower, capitalize, title, swapcase)
- Pythonで文字列の先頭・末尾の空白を削除(strip, lstrip, rstrip)
- Pythonで文字列の出現回数をカウント(count)
- Pythonで文字列をスライスで部分抽出
- Pythonで文字列を結合(join, +演算子)
- Pythonで文字列をフォーマット(format, f文字列 (Python 3.6以降), %演算子)