Micro-PEP: str.translate(None) to mean identity translation

Peter Otten __peter__ at web.de
Sat Apr 30 03:23:45 EDT 2005


M.E.Farmer wrote:

> Bengt Richter wrote:
>> Just thought None as the first argument would be both handy and
> mnemonic,
>> signifying no translation, but allowing easy expression of deleting
> characters,
>> e.g.,
>>
>>    s = s.translate(None, 'badcharshere')
>>
>> Regards,
>> Bengt Richter
> 
> What's wrong with :
> 
> s = s.replace('badchars', "")
> 
> It seems obvious to replace a char ( to me anyway ) with a blank
> string, rather than to 'translate' it to None.
> I am sure you have a reason what am I missing ?
> M.E.Farmer

>>> s = "NHoBwA RyAoSuB AsAeHeH AiBtH,A CnRoAwD HyBoAuC HdRoCnH'AtB"
>>> s.translate(None, "BADCHARS")
"Now you see it, now you don't"
>>> s.replace("BADCHARS", "")
"NHoBwA RyAoSuB AsAeHeH AiBtH,A CnRoAwD HyBoAuC HdRoCnH'AtB"

i. e. you have to replace() for every char in "BADCHARS":

>>> reduce(lambda x, y: x.replace(y, ""), "BADCHARS", s)
"Now you see it, now you don't"


+1, btw.

Peter



More information about the Python-list mailing list