Deleting specific characters from a string

John Hunter jdhunter at ace.bsd.uchicago.edu
Wed Jul 9 15:08:45 EDT 2003


>>>>> "Matt" == Matt Shomphe <MatthewS at HeyAnita.com> writes:

    Matt> Maybe a new method should be added to the str class, called
    Matt> "remove".  It would take a list of characters and remove
    Matt> them from the string:

you can use string translate for this, which is shorter and faster
than using the loop.

class rstr(str):
    _allchars = "".join([chr(x) for x in range(256)])
    def remove(self, chars):
        return self.translate(self._allchars, chars)

me = rstr('John Hunter')
print me.remove('ohn')

Also, you don't need to define a separate __init__, since you are nor
overloading the str default.

JDH





More information about the Python-list mailing list