cnst
cnst

Reputation: 27228

check if any members of a set start with a given prefix string in Python

In Python, I have a set of filenames and a given directory name (in a loop).

Both the filenames in the set and the given directory name are in the same namespace, e.g. I simply want to see if there are any member strings in the set that start with a given string / prefix.

What's the Python way to see if any filenames in a set start with a given directory prefix?

Upvotes: 3

Views: 2317

Answers (2)

mgilson
mgilson

Reputation: 310049

You can use the builtin any function:

any(x.startswith(prefix) for x in your_set)

This gives you a simple True or False -- depending on whether any of the items meets the criteria. If you want to know which element met your criteria, then you'll need next:

next((x for x in your_set if x.startswith(prefix)),None)

Of course, this only returns 1 element that meets your criteria -- If you need all of them, then see the answer by jsbueno.

Upvotes: 5

jsbueno
jsbueno

Reputation: 110476

You have to loop over all the set elements - you can get a lsit of these names by simply doing:

results = [element for element in your_set if element.startswith(your_prefix)]  

But by doing that you loose the fast acces set has to elements - since it is done with the hashes of strigns it stores. So, there is no fast way, using pure sets, to quickly check for substrings in its elements.

Upvotes: 0

Related Questions