杰瑞科技汇

Python str endswith方法如何精确匹配字符串后缀?

Of course! The Python str.endswith() method is a very useful and common string method. Let's break it down in detail.

Python str endswith方法如何精确匹配字符串后缀?-图1
(图片来源网络,侵删)

What is str.endswith()?

The str.endswith() method checks if a string ends with a specified suffix (another string). It returns True if the string ends with the suffix, and False otherwise.


Basic Syntax

string.endswith(suffix[, start[, end]])
  • string: The string you want to check.
  • suffix: The string or tuple of strings you want to check for at the end.
  • start (optional): The starting index from where the check should begin.
  • end (optional): The ending index (up to, but not including) where the check should stop.

Simple Examples

Let's start with the most common use case.

# A sample string to work with
filename = "my_report.pdf"
# Check if the string ends with ".pdf"
print(filename.endswith(".pdf"))  # Output: True
# Check if it ends with ".jpg"
print(filename.endswith(".jpg"))  # Output: False
# Check if it ends with "report.pdf"
print(filename.endswith("report.pdf")) # Output: True
# Check if it ends with "REPORT.PDF" (case-sensitive)
print(filename.endswith("REPORT.PDF")) # Output: False

Key takeaway: The method is case-sensitive. "Python".endswith("on") is True, but "Python".endswith("ON") is False.


Advanced Usage: start and end Parameters

These parameters allow you to check for a suffix within a slice of the string, without having to create a new substring first. This is more efficient.

Python str endswith方法如何精确匹配字符串后缀?-图2
(图片来源网络,侵删)

The syntax string[start:end] creates a slice from index start up to (but not including) index end. The endswith method checks if this slice ends with the suffix.

sentence = "The quick brown fox jumps over the lazy dog."
# Check if the last word is "dog."
# The last word starts at index 40 and goes to the end of the string.
# We can use the start parameter to begin checking from index 40.
print(sentence.endswith("dog.", 40))  # Output: True
# A more complex example: check if the word "brown" is present.
# "brown" starts at index 10 and ends at index 15.
# We want to see if the slice from index 10 to 15 ends with "rown".
print(sentence.endswith("rown", 10, 15)) # Output: True
# Let's check a slice that doesn't contain "rown"
print(sentence.endswith("rown", 10, 14)) # Output: False (the slice is "brow")

Checking for Multiple Suffixes with a Tuple

This is a powerful feature. If you pass a tuple of strings as the suffix, endswith() will check if the string ends with any of the strings in the tuple. It returns True as soon as it finds a match.

This is extremely useful for things like checking file extensions.

filename = "image.png"
# Check if the filename ends with any of these extensions
extensions = (".jpg", ".jpeg", ".png", ".gif", ".svg")
print(filename.endswith(extensions)) # Output: True
# Another example
document = "presentation.pptx"
valid_doc_extensions = (".docx", ".pdf", ".txt", ".ppt")
print(document.endswith(valid_doc_extensions)) # Output: False

Practical Use Cases

Validating File Extensions

This is the most common use case. It's a clean and readable way to check a file's type.

Python str endswith方法如何精确匹配字符串后缀?-图3
(图片来源网络,侵删)
def get_file_type(filename):
    if filename.endswith((".jpg", ".jpeg", ".png")):
        return "Image"
    elif filename.endswith((".mp4", ".mov", ".avi")):
        return "Video"
    elif filename.endswith((".pdf", ".docx")):
        return "Document"
    else:
        return "Unknown"
print(f"'cat.jpg' is a: {get_file_type('cat.jpg')}")
print(f"'report.pdf' is a: {get_file_type('report.pdf')}")
print(f"'script.py' is a: {get_file_type('script.py')}")
# Output:
# 'cat.jpg' is a: Image
# 'report.pdf' is a: Document
# 'script.py' is a: Unknown

Checking for Protocol Prefixes in URLs

You can check if a URL starts with http:// or https://.

url1 = "https://www.google.com"
url2 = "ftp://files.example.com"
print(url1.endswith("://")) # Output: True
print(url2.endswith("://")) # Output: True
# Or check for a specific protocol
print(url1.endswith("s://")) # Output: True (for https)
print(url1.endswith("http://")) # Output: False

Parsing Log Files

You can check the end of a log line to determine its severity level.

log_line = "2025-10-27 10:00:00 [ERROR] Disk space is full."
if log_line.endswith("ERROR]"):
    print("This is a critical error log!")
elif log_line.endswith("WARNING]"):
    print("This is a warning log.")
else:
    print("This is an informational log.")
# Output:
# This is a critical error log!

Common Pitfalls and How to Avoid Them

Pitfall 1: Forgetting Case-Sensitivity

# This will fail
user_input = "YES"
if user_input.endswith("yes"):
    print("Matched!") # This line will not be executed
# Solution 1: Make both the same case
if user_input.lower().endswith("yes"):
    print("Matched!") # Output: Matched!
# Solution 2: Use a case-insensitive regex (more advanced)
import re
if re.search(r'yes$', user_input, re.IGNORECASE):
    print("Matched with regex!") # Output: Matched with regex!

Pitfall 2: Using startswith() for Suffixes by Mistake

It's an easy typo to make. startswith() checks the beginning of a string.

filename = "report.pdf"
# Wrong method for checking the extension
if filename.startswith(".pdf"): # This is incorrect
    print("Is a PDF") # This will not print
# Correct method
if filename.endswith(".pdf"):
    print("Is a PDF") # Output: Is a PDF

endswith() vs. Slicing

You can achieve a similar result using string slicing, but endswith() is often more readable and can be more efficient, especially when checking multiple suffixes.

text = "hello world"
# Using slicing
if text[-5:] == "world":
    print("Slicing: It ends with 'world'") # Output: Slicing: It ends with 'world'
# Using endswith (often preferred for clarity)
if text.endswith("world"):
    print("endswith: It ends with 'world'") # Output: endswith: It ends with 'world'
# The real power of endswith comes with multiple suffixes
if text.endswith(("world", "earth", "planet")):
    print("Endswith with tuple: Match found!") # Output: Match found!
# Doing the same with slicing is much more verbose and less efficient
if text[-5:] == "world" or text[-5:] == "earth" or text[-5:] == "planet":
    print("Slicing with multiple conditions: Match found!")

Summary

Feature Description
Purpose To check if a string ends with a specific suffix.
Return Value True or False.
Case-Sensitive Yes. "File.TXT".endswith(".txt") is False.
Multiple Suffixes Yes, by passing a tuple of strings.
Slicing Yes, with optional start and end parameters.
Best For Clean, readable, and efficient code for file validation, URL parsing, and log analysis.
分享:
扫描分享到社交APP
上一篇
下一篇