[Python-ideas] More user-friendly version for string.translate()

Terry Reedy tjreedy at udel.edu
Fri Oct 28 10:28:49 EDT 2016


On 10/26/2016 6:17 PM, Chris Barker wrote:
> I"ve lost track of what (If anything) is actually being proposed here...
> so I"m going to try a quick summary:
>
>
> 1) an easy way to spell "remove all the characters other than these"

In other words, 'only keep these'.
We already have easy ways to create filtered strings.

 >>> s = 'kjskljkxcvnalsfjaweirKJZknzsnlkjsvnskjszsdscccjasfdjf'
 >>> s2 = ''.join(c for c in s if c in set('abc'))
 >>> s2
'caaccca'
 >>> s3 = ''.join(filter(lambda c: c in set('abc'), s))
 >>> s3
'caaccca'

I expect the first to be a bit faster.  Either can be wrapped in a 
keep() function.  If one has a translation dictionary d, use that in 
twice in the genexp.

 >>> d = {'a': '1', 'b': '3x', 'c': 'fum'}
 >>> ''.join(d[c] for c in s if c in d.keys())
'fum11fumfumfum1'

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list