Using endswith() with multiple strings in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Using endswith() with multiple strings in Python #

Pass a tuple to the endswith() method to use it with multiple strings. The endswith() method can be passed a tuple of suffixes and returns True if the string ends with any of the suffixes in the tuple.

main.py
my_str = 'bobbyhadz.com' if my_str.endswith(('com', 'org', 'net')): # 👇️ this runs print('The string ends with one of the suffixes') else: print('The string does NOT end with any of the suffixes') print(my_str.endswith(('com', 'org', 'net'))) # 👉️ True print(my_str.endswith(('a', 'b', 'c'))) # 👉️ False

The str.endswith method returns True if the string ends with the provided suffix, otherwise the method returns False.

main.py
my_str = 'bobbyhadz.com' print(my_str.endswith('com')) # 👉️ True print(my_str.endswith('abc')) # 👉️ False

The str.endswith() method can also be passed a tuple of suffixes and returns True if the string ends with any of the suffixes.

main.py
my_str = 'bobbyhadz.com' print(my_str.endswith(('com', 'org', 'net'))) # 👉️ True print(my_str.endswith(('a', 'b', 'c'))) # 👉️ False

Having two sets of parentheses next to one another might be a bit difficult to read, so you can extract the tuple into a variable.

main.py
my_str = 'bobbyhadz.com' suffixes = ('com', 'org', 'net') if my_str.endswith(suffixes): # 👇️ this runs print('The string ends with one of the suffixes') else: print('The string does NOT end with any of the suffixes') print(my_str.endswith(suffixes)) # 👉️ True

If the string ends with any of the suffixes, the str.endswith() method returns True, otherwise False is returned.

An alternative and more verbose approach is to use the any() function with a generator expression.

main.py
my_str = 'bobbyhadz.com' suffixes = ('com', 'org', 'net') if any(my_str.endswith(suffix) for suffix in suffixes): # 👇️ this runs print('The string ends with one of the suffixes') else: print('The string does NOT end with any of the suffixes')

We used a generator expression in the call to any().

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we call the str.endswith() method with the current suffix and return the result.

The any function takes an iterable as an argument and returns True if any element in the iterable is truthy.

If the iterable is empty or none of the elements in the iterable are truthy, the any function returns False.

If the condition is met at least once, the any() function short-circuits and returns True.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.