Skip to main content
 首页 » 编程设计

python之将字符串与列表中的单词匹配

2025年05月04日26cyq1162

我有一个后缀列表,我想检查我的单词是否以其中任何一个结尾,如果是,我想打印它,我正在执行以下操作:

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

my_list 是后缀列表。当我运行它时,它给我错误提示名称“word”未定义

请您参考如下方法:

any 返回一个 bool 值。 str.endswith 需要一个字符串或字符串的 tuple。

你可能想要这样的东西:

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

或者如果你真的想知道它匹配的是哪一个:

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