If a string contains a suffix from a list, how do I strip that specific suffix from the string?
<p>I have a list of strings and a list of suffixes. If a string contains one of the suffixes, how do I strip that specific one from the string? </p>

<pre><code>b = ["food", "stuffing", "hobbitses"]
y = ["ing", "es", "s", "ly"]


def stemming():
    for i in range(len(b)):
        if b[i].endswith(tuple(y)):
            b[i] = b[i] - #???
print b
</code></pre>

<p>You need to know which ending has been found, so you need to check them one at a time instead of trying to check them all at once. Once you have found an ending, you can chop it off using a slice.</p>

<pre><code>def stemming():
    for i, word in enumerate(b):
        for suffix in y:
            if word.endswith(suffix):
                b[i] = word[:-len(suffix)]
                break
</code></pre>

<p>A better approach would use a regular expression:</p>

<pre><code>import re
suffix = re.compile("(%s)$" % "|".join(y))

def stemming():
    for i, word in enumerate(b):
        b[i] = suffix.sub("", word)
</code></pre>

<p>Then you can easily do the stemming using a list comprehension:</p>

<pre><code>b = [suffix.sub("", w) for w in b]
</code></pre>

python string python-2.7 stemming