Reputation: 953
I want to replace letters in a character vector by other ones, using a dictionary created with dict
, as follows
import string
trans1 = str.maketrans("abc","cda")
trans = dict(zip("abc","cda"))
out1 = "abcabc".translate(trans1)
out = "abcabc".translate(trans)
print(out1)
print(out)
The desired output is "cdacda"
What I get is
cdacda
abcabc
Now out1
is this desired output, but out
is not. I can not figure out why this is the case. How can I use the dictionary created via dict
in the translate
function? So what do I have to change if I want to use translate
with trans
?
Upvotes: 7
Views: 16936
Reputation: 5549
str.translate
supports dicts perfectly well (in fact, it supports anything that supports indexing, i.e. __getitem__
) – it's 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'
Upvotes: 16
Reputation: 2738
The string.translate
doesn't 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.
Upvotes: 0
Reputation: 6070
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"}
Upvotes: 2