Python endswith() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 5 Examples
String Methods

What You’ll Learn

The endswith() method returns True if a string ends with a specified suffix, and False otherwise. It is one of the most practical string methods for checking file extensions, validating URL endings, and writing clean conditional logic without manual string slicing.

01

Suffix Check

Test how a string ends.

02

Returns bool

True or False result.

03

Tuple Suffixes

Match any of several endings.

04

start / end

Search within a slice.

05

File Types

Check .txt, .pdf, .jpg.

06

vs startswith()

End vs beginning checks.

Definition and Usage

In Python, endswith() is a built-in string method that checks whether the string’s ending matches a given suffix. For example, "document.txt".endswith(".txt") returns True, while "document.pdf".endswith(".txt") returns False. You can pass a tuple of suffixes to match any one of several endings in a single call.

💡
Beginner Tip

Prefer endswith() over slicing like s[-4:] == ".txt". It is more readable, handles edge cases safely, and supports checking multiple suffixes with a tuple.

📝 Syntax

The endswith() method accepts one required and two optional parameters:

python
string.endswith(suffix, start, end)

Syntax Rules

  • suffix — a string or tuple of strings to check at the end (required).
  • start — optional start index; the check runs on string[start:end].
  • end — optional end index; search stops before this position.
  • Return valueTrue or False; the original string is not modified.
  • Case-sensitive"A" and "a" are treated as different characters.

⚡ Quick Reference

ExpressionResult
"hello.py".endswith(".py")True
"hello.py".endswith(".txt")False
"photo.jpg".endswith((".jpg", ".png"))True
"File.TXT".endswith(".txt")False (case-sensitive)
"abcdef".endswith("ef", 0, 5)False (slice ends at "e")
Basic
name.endswith(".csv")

Single suffix check

Multiple
name.endswith((".jpg", ".png"))

Any suffix matches

Slice
text.endswith("ing", 0, 7)

Check within range

Negate
not url.endswith("/")

When suffix is absent

Examples Gallery

Run these examples in any Python 3 interpreter. Each one shows a common suffix-checking pattern.

📚 Getting Started

Check whether a filename ends with a specific extension.

Example 1 — Basic endswith()

Verify that a file is a text file by checking its extension.

python
filename = "document.txt"
is_text = filename.endswith(".txt")

print(f"File: {filename}")
print(f"Is text file: {is_text}")

How It Works

  • endswith(".txt") compares the last four characters of the string.
  • Returns True because "document.txt" ends with ".txt".
  • The filename string itself is not changed.

Example 2 — Checking Multiple Suffixes

Pass a tuple to match any of several image extensions in one call.

python
filename = "photo.jpg"
image_exts = (".jpg", ".jpeg", ".png", ".gif")

is_image = filename.endswith(image_exts)
print(f"{filename} is an image: {is_image}")

How It Works

Python checks each suffix in the tuple and returns True if any one matches. This is cleaner than chaining multiple or conditions.

📈 Practical Patterns

Slice boundaries, case rules, and comparison with startswith().

Example 3 — Using start and end

Check whether a portion of the string ends with a suffix.

python
text = "running fast"

full = text.endswith("ing")
partial = text.endswith("ing", 0, 7)

print("Full string: ", full)
print("First 7 chars:", partial)

How It Works

text[0:7] is "running", which ends with "ing". The full string ends with "fast", so the full check returns False.

Example 4 — Case Sensitivity

endswith() treats uppercase and lowercase as different.

python
filename = "Report.PDF"

print("Strict:     ", filename.endswith(".pdf"))
print("Insensitive:", filename.lower().endswith(".pdf"))

How It Works

Call .lower() on the filename (and use a lowercase suffix) when you want extension checks to ignore case differences.

Example 5 — endswith() vs startswith()

Use the right method for prefixes vs suffixes—including proper URL checks.

python
url = "https://example.com/page"
path = "/path/to/report.pdf"

print("URL uses HTTPS:  ", url.startswith("https://"))
print("URL ends with .com:", url.endswith(".com"))
print("Path is PDF:     ", path.endswith(".pdf"))

How It Works

  • startswith("https://") checks the URL prefix—the correct way to verify HTTPS.
  • url.endswith(".com") is False here because the URL ends with "/page", not ".com".
  • endswith(".pdf") correctly identifies the file extension in the path.

🚀 Common Use Cases

  • File extension filters — accept only .csv, .json, or image files in upload handlers.
  • Path validation — confirm a filepath ends with the expected extension before processing.
  • URL path checks — detect routes ending in "/" or specific path segments.
  • Data cleaning — skip or flag rows whose values end with unwanted characters.
  • Conditional logic — branch program flow based on how a string ends.

🧠 How endswith() Works

1

Python selects the search range

If start and end are given, the check runs on that slice; otherwise the full string is used.

Range
2

Suffix is compared at the end

Python checks whether the final characters of the range match the suffix (or any suffix in a tuple).

Compare
3

True or False is returned

No new string is created—only a boolean answer for your if statement or filter.

Result
=

Clear conditional logic

Readable suffix checks without manual index math or string slicing.

📝 Notes

  • endswith() is case-sensitive—normalize with .lower() when comparing file extensions.
  • An empty suffix "" always returns True (every string ends with an empty string).
  • For complex patterns (wildcards, optional parts), use the re module instead.
  • Do not use endswith("s") to check HTTPS—use startswith("https://") instead.

Conclusion

The endswith() method is a simple, readable way to test string endings in Python. Whether you are filtering files by extension, validating paths, or writing conditional logic, it gives you a clear boolean answer in one expression.

Remember: pass a tuple for multiple suffixes, use startswith() for prefixes, and call .lower() when case should not matter.

💡 Best Practices

✅ Do

  • Use a tuple to check several extensions at once
  • Include the dot in extensions: ".pdf" not "pdf"
  • Use .lower() for case-insensitive extension checks
  • Prefer endswith() over manual slicing
  • Use startswith() for URL schemes and path prefixes

❌ Don’t

  • Use endswith("s") to detect HTTPS URLs
  • Assume extension checks work across mixed-case filenames without normalizing
  • Use endswith() for regex-style pattern matching
  • Forget that endswith(".com") fails when the URL has a path after the domain
  • Confuse return value—it is bool, not a string or index

Key Takeaways

Knowledge Unlocked

Five things to remember about endswith()

Use these points when checking string endings in Python.

5
Core concepts
📁 02

File Extensions

.txt, .pdf, .jpg.

Use case
📝 03

Tuple Suffixes

Match any in one call.

Syntax
🔎 04

Slice Params

start and end optional.

Advanced
05

Case-Sensitive

Use lower() if needed.

Edge case

❓ Frequently Asked Questions

endswith() returns True if a string ends with the specified suffix, and False otherwise. It is commonly used to check file extensions, URL paths, and string endings.
string.endswith(suffix, start, end). suffix is the ending to check (or a tuple of endings). start and end optionally limit the search to a slice of the string.
Yes. Pass a tuple of suffix strings, such as (".jpg", ".png"). endswith() returns True if the string ends with any suffix in the tuple.
Yes. "File.TXT".endswith(".txt") returns False because uppercase T does not match. Use .lower() on both sides for a case-insensitive check.
endswith() checks the end of a string; startswith() checks the beginning. Use endswith() for file extensions and startswith() for prefixes like "https://".
No. It only reads the string and returns a boolean. The original string stays unchanged.

Explore More Python String Methods

Continue with expandtabs(), find(), and the rest of the string method reference.

Next: expandtabs() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

11 people found this page helpful