我试图计算以几个后缀结尾的单词的出现次数。我认为endswith
会接受一个可迭代的;不幸的是,它没有。以下是代码段:
s = 'like go goes likes liked liked liking likes like'
lst = s.split()
suffixes = ['s', 'es', 'ies', 'ed', 'ing']
counter = 0
prompt = 'like'
for x in lst:
if x.startswith(prompt) and x.endswith(any(suffix for suffix in suffixes)):
counter += 1
执行结束时counter
的值应为4
。这是显示的错误消息:
TypeError: endswith first arg must be str or a tuple of str, not bool
如何让上述代码生效?
答案 0 :(得分:5)
any
函数返回bool值,但str.startswith
需要字符串或字符串元组。
您只需将列表转换为元组并将其传递给startswith
:
x.endswith(tuple(suffixes))