TypeError:endswith first arg必须是str或str的元组,而不是bool

时间:2015-10-01 13:41:53

标签: python python-3.x count boolean ends-with

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

如何让上述代码生效?

1 个答案:

答案 0 :(得分:5)

any函数返回bool值,但str.startswith需要字符串或字符串元组。

您只需将列表转换为元组并将其传递给startswith

即可
x.endswith(tuple(suffixes))