我有一个后缀列表,我想检查我的单词是否以其中任何一个结尾,如果是,我想打印它,我正在执行以下操作:
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
关于python - 将字符串与列表中的单词匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15127744/