Deleting specific characters from a string

Jeff Hinrichs jlh at cox.net
Thu Jul 10 06:35:39 CEST 2003


"John Hunter" <jdhunter at ace.bsd.uchicago.edu> wrote in message
news:mailman.1057789156.27025.python-list at python.org...
> >>>>> "Behrang" == Behrang Dadsetan <ben at dadsetan.com> writes:
>
>     Behrang> is going to finally be what I am going to use.  I not
>     Behrang> feel lambdas are so readable, unless one has serious
>     Behrang> experience in using them and python in general. I feel it
>     Behrang> is acceptable to add a named method that documents with
>     Behrang> its name what it is doing there.
>
> If you want to go the functional programing route, you can generalize
> your function somewhat using a callable class:
>
> class remove_char:
>     def __init__(self,remove):
>         self.remove = dict([ (c,1) for c in remove])
>
>     def __call__(self,c):
>         return not self.remove.has_key(c)
>
> print filter(remove_char('on'), 'John Hunter')
I've been following this thread, and on a whim I built a test harness to
time the different ideas that have been put forth in this thread.  I will
post complete results tomorrow on the web but the short version is that
using the .replace method is the overall champ by quite a bit.  Below is the
function I tested against the others in the harness:

def stringReplace(s,c):
"""Remove any occurrences of characters in c, from string s
    s - string to be filtered, c - characters to filter"""
    for a in c:
        s = s.replace(a,'')
    return s

It wins also by being easy to understand, no filter or lambda.  Not that I
have anything against filter or lambda, but when the speediest method is the
most readable, that solution is definitely the Pythonic champ. :)

-Jeff Hinrichs







More information about the Python-list mailing list