TypeError: endswith first arg must be str or a tuple of str, not bool

TypeError: endswith first arg must be str or a tuple of str, not bool

我试图计算以多个后缀结尾的单词的出现次数。我认为 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

如何让上面的代码工作?

any 函数 returns 一个 bool 值,但是 str.startswith 需要一个字符串或一个字符串元组。

您可以将列表转换为元组并将其传递给 startswith:

x.endswith(tuple(suffixes))