Deleting specific characters from a string

Matt Shomphe MatthewS at HeyAnita.com
Wed Jul 9 14:44:02 EDT 2003


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


class RemoveString(str):
    def __init__(self, s=None):
        str.__init__(self, s)
    def remove(self, chars):
        s = self
        for c in chars:          
            s = s.replace(c, '')
        return(s)

if __name__ == '__main__':
    r = RemoveString('abc')
    e = r.remove('c')
    print r, e 
    # prints "abc ab" -- it's not "in place" removal

M@
            


Behrang Dadsetan <ben at dadsetan.com> wrote in message news:<begfb3$7j6$1 at online.de>...
> Hi all,
> 
> I would like deleting specific characters from a string.
> As an example, I would like to delete all of the '@' '&' in the string 
> 'You are ben at orange?enter&your&code' so that it becomes 
> 'benorange?enteryourcode'.
> 
> So far I have been doing it like:
> str = 'You are ben at orange?enter&your&code'
> str = ''.join([ c for c in str if c not in ('@', '&')])
> 
> but that looks so ugly.. I am hoping to see nicer examples to acheive 
> the above..
> 
> Thanks.
> Ben.




More information about the Python-list mailing list