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

Mohammed picture Mohammed · Oct 1, 2015 · Viewed 16.1k times · Source

I was trying to count the occurrences of words which end with several suffixes. I thought that endswith would accept an iterable; unfortunately, it did not. Below is the code snippet:

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

The value of counter should be 4 at the end of the execution. This is the error message which is displayed:

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

How can I get the above code to work?

Answer

kasravnd picture kasravnd · Oct 1, 2015

The any function returns a bool value, but str.startswith requires a string or a tuple of strings.

You can just convert your list to a tuple and pass it to startswith:

x.endswith(tuple(suffixes))