Using startswith() with multiple strings in Python

avatar

Borislav Hadzhiev

Last updated: Sep 23, 2022

banner

Photo from Unsplash

Using startswith() with multiple strings in Python #

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

main.py
my_str = 'bobbyhadz.com' if my_str.startswith(('bobby', 'ab', 'cd')): # 👇️ this runs print('The string starts with one of the prefixes') else: print('The string does NOT start with any of the prefixes') print(my_str.startswith(('bobby', 'ab', 'cd'))) # 👉️ True print(my_str.startswith(('ab', 'cd'))) # 👉️ False

The str.startswith method returns True if the string starts with the provided prefix, otherwise the method returns False.

main.py
my_str = 'bobbyhadz.com' print(my_str.startswith('bobby')) # 👉️ True print(my_str.startswith('abc')) # 👉️ False
The str.startswith() method can also be passed a tuple of prefixes and returns True if the string starts with any of the prefixes.
main.py
my_str = 'bobbyhadz.com' print(my_str.startswith(('bobby', 'ab', 'cd'))) # 👉️ True print(my_str.startswith(('ab', 'cd'))) # 👉️ 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' prefixes = ('bobby', 'ab', 'cd') if my_str.startswith(prefixes): # 👇️ this runs print('The string starts with one of the prefixes') else: print('The string does NOT start with any of the prefixes') print(my_str.startswith(prefixes)) # 👉️ True

If the string starts with any of the prefixes, the str.startswith() 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' prefixes = ('bobby', 'ab', 'cd') if any(my_str.startswith(prefix) for prefix in prefixes): # 👇️ this runs print('The string starts with one of the prefixes') else: print('The string does NOT start with any of the prefixes')

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.startswith() method with the current prefix 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.