2

I'm looking for a python module that would help to test if a string is in a list of formatted string. I can't find the exact words to explain my problem (that's probably why I didn't find anything) so here is an example :

REGISTERED_KEYS = (
    'super_key',
    'key_ending_with_anything_*',
    'anything'
)

is_key_registered("super_key", REGISTERED_KEYS)
>> True

is_key_registered("wrong_key", REGISTERED_KEYS)
>> False

is_key_registered("key_ending_with_anything_foobar", REGISTERED_KEYS)
>> True

The thing is not to simply check if a string is in a list but it's also to allow string formatting. I may have to use regexp but I wanted to know if there's an existing module that does this (as it seems to be a common need). Edit : the format of my REGISTERED_KEYS doesn't have to me the one I've written. Can be regex.

Thanks

martync
  • 350
  • 4
  • 15

2 Answers2

3

If you want to use file wildcards, then use the appropriate library for matching filenames: fnmatch

import fnmatch

def is_key_registered(foo, keys):
    return any(fnmatch.fnmatch(foo, key) for key in keys)
eumiro
  • 207,213
  • 34
  • 299
  • 261
0

You can browse all key an check them:

import re


def is_key_registered(key, keys):
    for _ in keys:
        if re.search(_, key):
            return True
Kenly
  • 24,317
  • 7
  • 44
  • 60