Deleting specific characters from a string
Behrang Dadsetan
ben at dadsetan.com
Wed Jul 9 16:09:11 EDT 2003
Donn Cave wrote:
> In article <5ab0af73.0307091044.254f5aab at posting.google.com>,
> MatthewS at HeyAnita.com (Matt Shomphe) wrote:
>>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:
> Check out the translate function - that's what its optional
> deletions argument is for.
>>> str = 'You are Ben at orange?enter&your&code'
>>> str.translate(string.maketrans('',''), '@&')
and
>>> str.replace('&', '').replace('@', '')
are also ugly...
The first version is completely unreadable. I guess my initial example
''.join([ c for c in str if c not in ('@', '&')]) was easier to read
than the translate (who would guess -without having to peek in the
documentation of translate- that that line deletes @ and &?!) but I am
not sure ;)
while the second becomes acceptable. The examples you gave me use the
string module.
I think I read somewhere that the methods of the object should rather be
used than the string module. Is that right?
Thanks anyhow, I will go for the replace(something, '') method.
Ben.
More information about the Python-list
mailing list