銀河鉄道

【Python】拡張子の存在確認|endswith + lower(Method Chaining)

サムネイル
[Python]endswith+ lower
メソッドチェーンを
使う

メソッドチェーン?

メソッドをチェーンのようにくっつけるの

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"))     # False

Use 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"))   # False
  • Checks if the string ends with the given suffix. Returns True or False.
  • 文字列が指定した語尾で終わっているかどうかを判定し、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"))    # False
  • target_name.lower().endswith(expected_extension.lower())
  • target_name を小文字に変換したうえで、expected_extension も小文字にして、両者を末尾比較する。

Referenced Insights & Citations

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.
オブジェクト指向言語では読みやすさのために チェーン が使われる

著者

author
月うさぎ

編集後記:
この記事の内容がベストではないかもしれません。

記事一覧