Explain Codes LogoExplain Codes Logo

Str.startswith with a list of strings to test for

python
prompt-engineering
performance
functions
Alex KataevbyAlex Kataev·Mar 7, 2025
TLDR

Swiftly ascertain whether a string commences with any prefix in a list employing these methods:

  • any() with a generator: Concise and idiomatic.

    any(s.startswith(prefix) for prefix in prefixes) # pythonic art at its best
  • next() with short-circuiting: Exit on first match for performance.

    next((True for prefix in prefixes if s.startswith(prefix)), False) # Next stop, first match!
  • map() function: Unleash the power of functional programming.

    any(map(s.startswith, prefixes)) # It's a kind of map-gic

Each approach will return True if s starts with any of the provided prefixes, otherwise, you get a False.

Tuples: The unsung hero

When dealing with str.startswith() and a list of starter strings, consider using a tuple data type. As tuples are immutable, Python can optimize the operations more efficiently. But don't worry, transforming your list into a tuple is no big deal:

prefixes = tuple(prefix_list) # See, nothing to be tuple-d about

start and end, not just a cheesy romance

The str.startswith() function doesn't just check the entirety of the strings. The optional start and end parameters can help you verify prefixes within certain substrings. Yeah, it's that particular:

string = "unbelievable" prefixes = ("un", "believ") print(string.startswith(prefixes, 3)) # 'un'believably specific, isn't it?

Let's drop the cases

Foiled by uppercase prefixes when your string is yelling in caps lock? Have no fear, case-insensitive checks are here. This lifesaver combo of str.lower() and str.startswith() does the trick:

s = "Hello World" prefixes = ("hello", "hi") print(any(s.lower().startswith(prefix.lower()) for prefix in prefixes)) # Lower your guards, cases don't scare us!

The next() big thing

Don't underestimate the power of next(). Yes, it's not as commonly used, but when it comes to performance benefits, it packs a punch. Especially for a long list of prefixes, it'll bail on the first match:

first_match = next((prefix for prefix in prefixes if s.startswith(prefix)), None) # No prefix left behind!

Functional and regex alternatives

Besides the usual suspects, you’ve got other options like filter() and regular expressions at your disposal for a more flexible prefix matching.

Signs of a functional programmer

filter() gives a lean, mean, and functional way to scavenge all strings matching any prefix:

matching = filter(lambda item: any(item.startswith(prefix) for prefix in prefixes), strings) print(list(matching)) # Who's filtering who now?

Regex: The wildcard solution

Complex patterns knocking on your door? Show them the power of regular expressions. As versatile as a Swiss army knife, it can handle non-standard patterns that our good ol' str.startswith simply can't match:

import re pattern = re.compile(r'^(prefix1|prefix2)') # The power of regex compels you! print(pattern.match(s) is not None)

It's time...for performance

Remember, the effectiveness of individual methods might vary based on your input size and frequency of matches. So, pull up your sleeves and take timeit for a spin. The stopwatch for your code!