Remove substring only at the end of string

def rchop(s, suffix):
    if suffix and s.endswith(suffix):
        return s[:-len(suffix)]
    return s

somestring = 'this is some string rec'
rchop(somestring, ' rec')  # returns 'this is some string'

Since you have to get len(trailing) anyway (where trailing is the string you want to remove IF it's trailing), I'd recommend avoiding the slight duplication of work that .endswith would cause in this case. Of course, the proof of the code is in the timing, so, let's do some measurement (naming the functions after the respondents proposing them):

import re

astring = 'this is some string rec'
trailing = ' rec'

def andrew(astring=astring, trailing=trailing):
    regex = r'(.*)%s$' % re.escape(trailing)
    return re.sub(regex, r'\1', astring)

def jack0(astring=astring, trailing=trailing):
    if astring.endswith(trailing):
        return astring[:-len(trailing)]
    return astring

def jack1(astring=astring, trailing=trailing):
    regex = r'%s$' % re.escape(trailing)
    return re.sub(regex, '', astring)

def alex(astring=astring, trailing=trailing):
    thelen = len(trailing)
    if astring[-thelen:] == trailing:
        return astring[:-thelen]
    return astring

Say we've named this python file a.py and it's in the current directory; now, ...:

$ python2.6 -mtimeit -s'import a' 'a.andrew()'
100000 loops, best of 3: 19 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.jack0()'
1000000 loops, best of 3: 0.564 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.jack1()'
100000 loops, best of 3: 9.83 usec per loop
$ python2.6 -mtimeit -s'import a' 'a.alex()'
1000000 loops, best of 3: 0.479 usec per loop

As you see, the RE-based solutions are "hopelessly outclassed" (as often happens when one "overkills" a problem -- possibly one of the reasons REs have such a bad rep in the Python community!-), though the suggestion in @Jack's comment is way better than @Andrew's original. The string-based solutions, as expected, shing, with my endswith-avoiding one having a miniscule advantage over @Jack's (being just 15% faster). So, both pure-string ideas are good (as well as both being concise and clear) -- I prefer my variant a little bit only because I am, by character, a frugal (some might say, stingy;-) person... "waste not, want not"!-)


If speed is not important, use regex:

import re

somestring='this is some string rec'

somestring = re.sub(' rec$', '', somestring)