Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String translate using dict

Tags:

python

string

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?

like image 623
user3825755 Avatar asked Dec 10 '22 17:12

user3825755


1 Answers

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'
like image 168
ash Avatar answered Dec 13 '22 07:12

ash