'string'.strip(chars)-like function that removes from the middle?

Terry Reedy tjreedy at udel.edu
Tue Jun 17 19:51:52 CEST 2008

Peter Otten wrote:
> Terry Reedy wrote:
>> Cédric Lucantis wrote:
>>> I don't see any string method to do that
>>  >>> 'abcde'.translate(str.maketrans('','','bcd'))
>> 'ae'
>> I do not claim this to be better than all the other methods,
>> but this pair can also translate while deleting, which others cannot.
> You should mention that you are using Python 3.0 ;) 
> The 2.5 equivalent would be
>>>> u"abcde".translate(dict.fromkeys(map(ord, u"bcd")))
> u'ae'

Sorry.  I did not realize that the maketrans function had not then been 
moved from the string module to the str class object, unlike nearly all 
other functions from string, including the translate function.  I also 
misremembered that maketrans did not have the new third delete param. 
What I did do once long ago was something like

 >>> import string
 >>> a = 'abcde'.translate(string.maketrans('bd','**'))
 >>> a.replace('*','')

which is not very nice.


More information about the Python-list mailing list