python – String translate using dict

python – String translate using dict

str.translate supports dicts perfectly well (in fact, it supports anything that supports indexing, i.e. __getitem__) – its just that the key has to be the ordinal representation of the character, not the character itself.

Compare:

>>> abc.translate({a: d})
abc
>>> abc.translate({ord(a): d})
dbc

I do not think the method translate will accept a dictionary object. Aditionlly, you should look at what you are creating:

>>> dict(zip(abc,cda))
{c: a, a: c, b: d}

I do not think that is what you wanted. zip pairs off correspondingly indexed elements from the first and second argument.

You could write a work around:

def translate_from_dict(original_text,dictionary_of_translations):
    out = original_text
    for target in dictionary_of_translations:
        trans = str.maketrans(target,dictionary_of_translations[target])
        out = out.translate(trans)
    return out

trans = {abc:cda}
out = translate_from_dict(abcabc,trans)
print(out)

Usage of the dict function to create the dictionary. Read the function definition.

>>> dict([(abc,cda)])
{abc:cda}

python – String translate using dict

The string.translate doesnt support dictionaries as arguments:

translate(s, table, deletions=)
    translate(s,table [,deletions]) -> string

    Return a copy of the string s, where all characters occurring
    in the optional argument deletions are removed, and the
    remaining characters have been mapped through the given
    translation table, which must be a string of length 256.  The
    deletions argument is not allowed for Unicode strings.

So, you have to write your own function.

Also, revise your code as it wont run in any python version that I know. It has at least 2 exceptions.

Leave a Reply

Your email address will not be published. Required fields are marked *