【Python】拡張子の存在確認|endswith + lower(Method Chaining)
作成日:2025-09-29
更新日:2025-09-29

メソッドチェーンを
使う
使う

メソッドチェーン?

メソッドをチェーンのようにくっつけるの
str.lower().endswith()
def extension_exists(target_name: str, expected_extension: str) -> bool:
"""
Check if target_name ends with expected_extension (case-insensitive).
target_name の末尾が expected_extension と一致するか判定(大文字小文字無視)
"""
return target_name.lower().endswith(expected_extension.lower())
# --- Usage Examples / 使用例 ---
print(extension_exists("Report.XLSX", ".xlsx")) # True
print(extension_exists("photo.JPG", ".jpg")) # True
print(extension_exists("data.csv", ".txt")) # FalseUse str.lower().endswith() in Python for case-insensitive suffix checks.
Pythonでは、大文字小文字を無視した語尾判定には str.lower().endswith() を使う

ドットでつなげるのは何?

それがチェーン
Method Chaining|連鎖
連鎖 = 1行で実現する
lower()- 文字列をすべて小文字に変換。
endswith()- その文字列が特定の語尾で終わっているか判定。
- 大文字小文字を無視した語尾判定を1行でおこなう
1. lower() メソッド
print("Report.XLSX".lower()) # "report.xlsx"Converts all characters in a string to lowercase.- 文字列中のすべての文字を小文字に変換する。
2. endswith() メソッド
print("report.xlsx".endswith(".xlsx")) # True
print("report.xlsx".endswith(".csv")) # FalseChecks if the string ends with the given suffix. ReturnsTrueorFalse.- 文字列が指定した語尾で終わっているかどうかを判定し、
TrueまたはFalseを返す。

2つのメソッドをチェーンのようにくっつける
3. 連鎖(Method Chaining)
def extension_exists(target_name: str, expected_extension: str) -> bool:
return target_name.lower().endswith(expected_extension.lower())
print(extension_exists("PHOTO.JPG", ".jpg")) # True
print(extension_exists("DATA.CSV", ".TXT")) # Falsetarget_name.lower().endswith(expected_extension.lower())target_nameを小文字に変換したうえで、expected_extensionも小文字にして、両者を末尾比較する。
Referenced Insights & Citations
- Python Docs. (n.d.). str.lower. Retrieved from https://docs.python.org/3/library/stdtypes.html#str.lower
- Python Docs. (n.d.). str.endswith. Retrieved from https://docs.python.org/3/library/stdtypes.html#str.endswith
Vocabulary
| Method Chaining | メソッド連鎖 | Calling methods one after another in a single expression. ひとつの式の中で複数のメソッドを順番に呼び出すこと |
| lower() | 小文字変換 | Converts all characters in a string to lowercase. 文字列を小文字に変換する |
| endswith() | 末尾一致判定 | Checks if a string ends with the given suffix. 語尾が指定文字列で終わるか確認する |
| Case-insensitive | 大文字小文字を無視 | Comparison that ignores uppercase/lowercase. 大文字小文字を区別しない比較 |
Prefer method chaining in object-oriented languages for readability.
オブジェクト指向言語では読みやすさのために チェーン が使われる
2025-09-29
編集後記:
この記事の内容がベストではないかもしれません。
記事一覧
-

[Python]inString 【Python】指定の文字列が含まれているか|in -

[Python]Excelto CSV 【Python】ExcelからCSVに書き出す|pandas,csv -

[Python]pathlib存在確認 【Python】フォルダとファイルの存在確認|pathlib -

[Python]Search or Scanfor Excel book 【Python】ファイル名からExcelブックを取得する|openpyxl or win32com -

[Python]Stringsplit 【Python】文字列を抜き出す|.split -

[Python]Write a 1D arrayvia pandas 【Python】Excelに書き出す|pandas.ExcelWriter