简体   繁体   中英

Python test string in list of string format

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM