Python String endswith() Method

When I was working on a project, I needed to filter files in a directory based on their extensions. I had hundreds of files with different formats like .txt, .csv, .json, and .pdf.

The challenge was to identify and process only specific file types efficiently. That’s when I discovered the power of Python’s endswith() method.

In this comprehensive guide, I’ll show you everything you need to know about the endswith() method. From basic syntax to advanced use cases, you’ll learn how to use this string method effectively.

What is the Python endswith() Method?

The endswith() method is a built-in string method that checks if a string ends with a specified suffix. It returns True if the string ends with the given suffix, and False otherwise.

This method is incredibly useful for validation, file processing, data cleaning, and many other real-world applications.

Basic Syntax and Parameters

The basic syntax of the endswith() method is easy:

string.endswith(suffix, start, end)

Let me break down each parameter:

  • suffix: The substring you want to check at the end (required)
  • start: Starting position for the search (optional)
  • end: Ending position for the search (optional)

Method 1 – Basic Usage with Single Suffix

The most common way to use Python’s endswith() method is with a single suffix. Here’s how I typically use it in my projects:

# Check if email addresses are from Gmail
email1 = "john.smith@gmail.com"
email2 = "sarah.johnson@yahoo.com"
email3 = "mike.wilson@gmail.com"

# Check if emails end with gmail.com
print(f"{email1} is Gmail: {email1.endswith('@gmail.com')}")
print(f"{email2} is Gmail: {email2.endswith('@gmail.com')}")
print(f"{email3} is Gmail: {email3.endswith('@gmail.com')}")

You can see the output in the screenshot below.

python endswith

This method is perfect when you need to check for a specific ending pattern.

Method 2 – Use Multiple Suffixes with Tuple

One of the most useful features of endswith() is its ability to check multiple suffixes simultaneously. I use this approach frequently when processing different file types:

# List of files in a project directory
files = [
    "data_analysis.py",
    "config.json",
    "readme.txt",
    "results.csv",
    "main.py",
    "settings.xml",
    "backup.zip"
]

# Check for multiple file extensions
code_files = []
data_files = []

for file in files:
    if file.endswith(('.py', '.js', '.html', '.css')):
        code_files.append(file)
    elif file.endswith(('.csv', '.json', '.xml', '.txt')):
        data_files.append(file)

print("Code files:", code_files)
print("Data files:", data_files)

You can see the output in the screenshot below.

endswith python

This approach eliminates the need for multiple or conditions and makes your code cleaner.

Method 3 – Use Start and End Parameters

Sometimes you need to check only a portion of a string. The start and end parameters come in handy for this:

# US phone numbers with different formats
phone_numbers = [
    "+1-555-123-4567",
    "+1-555-987-6543",
    "+1-555-246-8135"
]

# Check if area code ends with '55' (positions 3-6 contain area code)
for phone in phone_numbers:
    # Extract area code part and check if it ends with '55'
    area_code_part = phone[3:7]  # Gets "555-"
    ends_with_55 = phone.endswith('55', 3, 6)  # Check positions 3-6

    print(f"Phone: {phone}")
    print(f"Area code part: {area_code_part}")
    print(f"Ends with '55': {ends_with_55}")
    print("-" * 30)

You can see the output in the screenshot below.

python string endswith

Using endswith() with start and end parameters lets you check specific string segments without slicing manually.

Real-World Applications

Let me show you the real-world application of the endswith() method

File Processing and Organization

Here’s a practical example I often use for organizing files by type:

import os

def organize_files_by_extension(file_list):
    """Organize files into categories based on their extensions"""

    categories = {
        'Images': [],
        'Documents': [],
        'Videos': [],
        'Audio': [],
        'Code': [],
        'Others': []
    }

    for file in file_list:
        if file.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp')):
            categories['Images'].append(file)
        elif file.endswith(('.pdf', '.doc', '.docx', '.txt', '.rtf')):
            categories['Documents'].append(file)
        elif file.endswith(('.mp4', '.avi', '.mov', '.wmv', '.flv')):
            categories['Videos'].append(file)
        elif file.endswith(('.mp3', '.wav', '.flac', '.aac')):
            categories['Audio'].append(file)
        elif file.endswith(('.py', '.js', '.html', '.css', '.java', '.cpp')):
            categories['Code'].append(file)
        else:
            categories['Others'].append(file)

    return categories

# Sample file list
files = [
    "vacation_photo.jpg",
    "report.pdf",
    "presentation.pptx",
    "music.mp3",
    "video_tutorial.mp4",
    "main.py",
    "styles.css",
    "data.csv"
]

organized = organize_files_by_extension(files)

for category, file_list in organized.items():
    if file_list:
        print(f"{category}: {file_list}")

Using endswith() helps classify and organize files efficiently based on their extensions.

URL Validation and Processing

In web development, I frequently use endswith() for URL validation:

def categorize_urls(urls):
    """Categorize URLs based on their endings"""

    social_media = []
    government = []
    educational = []
    commercial = []

    for url in urls:
        if url.endswith(('.gov', '.gov/')):
            government.append(url)
        elif url.endswith(('.edu', '.edu/')):
            educational.append(url)
        elif any(social in url for social in ['facebook.com', 'twitter.com', 'instagram.com']):
            social_media.append(url)
        else:
            commercial.append(url)

    return {
        'Social Media': social_media,
        'Government': government,
        'Educational': educational,
        'Commercial': commercial
    }
# Sample URLs
urls = [
    "https://www.whitehouse.gov",
    "https://www.harvard.edu",
    "https://www.facebook.com/profile",
    "https://www.amazon.com",
    "https://www.nasa.gov/missions",
    "https://www.mit.edu/research"
]

categorized = categorize_urls(urls)
for category, url_list in categorized.items():
    if url_list:
        print(f"{category}:")
        for url in url_list:
            print(f"  - {url}")
        print()

endswith() makes it simple to categorize and validate URLs by their domain suffixes.

Data Validation in Forms

Here’s how I use endswith() for validating user input in forms:

def validate_user_data(data):
    """Validate user registration data"""

    errors = []
    # Validate email domain
    email = data.get('email', '')
    allowed_domains = ('@gmail.com', '@yahoo.com', '@outlook.com', '@company.com')

    if not email.endswith(allowed_domains):
        errors.append(f"Email must end with one of: {', '.join(allowed_domains)}")

    # Validate phone number format
    phone = data.get('phone', '')
    if not phone.endswith(tuple(str(i) for i in range(10))):
        errors.append("Phone number must end with a digit")

    # Validate username restrictions
    username = data.get('username', '')
    if username.endswith(('.admin', '.root', '.system')):
        errors.append("Username cannot end with system reserved suffixes")
    return errors

# Test data
test_users = [
    {
        'email': 'john@gmail.com',
        'phone': '555-123-4567',
        'username': 'john_doe'
    },
    {
        'email': 'sarah@example.com',  # Invalid domain
        'phone': '555-123-456X',       # Invalid phone
        'username': 'admin.admin'      # Invalid username
    }
]
for i, user in enumerate(test_users, 1):
    print(f"User {i} Validation:")
    errors = validate_user_data(user)

    if errors:
        print("Errors found:")
        for error in errors:
            print(f"  - {error}")
    else:
        print("All validations passed!")
    print("-" * 40)

With endswith(), you can easily enforce specific input rules and formats in user-submitted data.

After working with the endswith() method for over a decade, I can confidently say it’s one of the most practical string methods in Python. Whether you’re processing files, validating user input, or organizing data, this method provides a clean and efficient solution.

The key to mastering endswith() lies in understanding its flexibility – from simple single-suffix checks to complex multi-suffix validation with positional parameters. Remember to consider case sensitivity, use tuples for multiple suffixes, and always validate your inputs when working with user data.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.