简体   繁体   中英

Match a string to a word in list

I have a list of suffixes and I want to check if my word ends with any of those and if it does I want to print it, I am doing the following:

if(string.endswith(any(word in my_list))):
        print string
        print" "
        print word

my_list is the list of suffixes. When I run it, it gives me error saying name 'word' is not defined

any returns a boolean value. str.endswith expects either a string or a tuple of strings.

You probably want something like:

if s.endswith(tuple(my_list)):
   print string

or if you actually want to know which one it matched:

suffix = next((word for word in my_list if s.endswith(word)),False)
if suffix:
    print word, suffix

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