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

Chris Angelico rosuav at gmail.com
Thu Oct 27 00:33:31 EDT 2016


On Thu, Oct 27, 2016 at 8:48 AM, Mikhail V <mikhailwas at gmail.com> wrote:
> On 26 October 2016 at 20:58, Stephen J. Turnbull
> <turnbull.stephen.fw at u.tsukuba.ac.jp> wrote:
>>import collections
>>def translate_or_drop(string, table):
>>    """
>>    string: a string to process
>>    table: a dict as accepted by str.translate
>>    """
>>    return string.translate(collections.defaultdict(lambda: None, **table))
>
>>All OK now?
>
> Not really. I tried with a simple example
> intab = "ae"
> outtab = "XM"
> table = string.maketrans(intab, outtab)
> collections.defaultdict(lambda: None, **table)
>
> an this gives me
> TypeError: type object argument after ** must be a mapping, not str
>
> But I probably I misunderstood the idea.

You're 99% of the way to understanding it. Try the exercise again in
Python 3. You don't have string.maketrans (which creates a 256-byte
translation mapping) - instead, you use a dictionary.

ChrisA


More information about the Python-ideas mailing list