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
?
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With