Deleting specific characters from a string

Behrang Dadsetan ben at dadsetan.com
Wed Jul 9 17:36:03 EDT 2003


Walter Dörwald wrote:

> Behrang Dadsetan wrote:
>
>> 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..
>
>
> What about the following:
>
> str = 'You are ben at orange?enter&your&code'
> str = filter(lambda c: c not in "@&", str)
>
> Bye,
>    Walter Dörwald 

def isAcceptableChar(character):
    return charachter in "@&"

str = filter(isAcceptableChar, str)

is going to finally be what I am going to use.
I not feel lambdas are so readable, unless one has serious experience in 
using them and python in general. I feel it is acceptable to add a named 
method that documents with its name what it is doing there.

But your example would probably have been my choice if I was more 
familiar with that type of use and the potential readers of my code were 
also familiar with it. Many thanks!

Ben.





More information about the Python-list mailing list