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

Moh*_*med 2 python boolean count python-3.x 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
Run Code Online (Sandbox Code Playgroud)

的值counter4在执行结束时。这是显示的错误消息:

TypeError: endswith first arg must be str or a tuple of str, not bool
Run Code Online (Sandbox Code Playgroud)

如何使以上代码起作用?

Kas*_*mvd 6

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

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

x.endswith(tuple(suffixes))
Run Code Online (Sandbox Code Playgroud)

  • @穆罕默德为什么?''liking''不是以''like'`开头。 (2认同)