Deleting specific characters from a string

Duncan Booth duncan at
Wed Jul 9 10:12:43 CEST 2003

Behrang Dadsetan <ben at> wrote in news:begfb3$7j6$1 at

> 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..

Use the third argument to string.translate:

>>> identity = string.maketrans("","")
>>> string.translate('You are ben at orange?enter&your&code', identity, "@&")
'You are benorange?enteryourcode'

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list