may be a bug in string.rstrip

Sion Arrowsmith siona at chiark.greenend.org.uk
Fri Nov 23 09:24:31 EST 2007


Scott SA  <pydev at rscorp.ab.ca> wrote:
>    >>> string.replace('120.exe','.exe','')
>    '120'

Don't use string.replace(), use the replace method of strings:
>>> '120.exe'.replace('.exe', '')
'120'

>... but it has a side-effect of mid-string replacements:
>
>    >>> string.replace('123.exe.more','.exe','')
>    '123.more'

>>> s = '120.exe.more'
>>> (s+'\0').replace('.exe' + '\0', '').rstrip('\0')
'120.exe.more'

Yeah, it's a little fragile if you have embedded NULLs. In
which case, you can always test with endswith():

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

You can even make it case-insensitive:

def istrip_suffix(s, suffix):
    if s.lower().endswith(suffix.lower()):
        return s[:-len(suffix)]
    return s

Point being, don't reach for regular expression solutions too
quickly. They will almost certainly be (a) slower and (b) harder
for other people to read.

-- 
\S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
   "Frankly I have no feelings towards penguins one way or the other"
        -- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump



More information about the Python-list mailing list