0
Why does translate() working like this?
What is the reason for the output? print('abcd'.translate({'a':'1','b':'2','c':'3','d':'4'})) OUTPUT: abcd
2 Respuestas
+ 3
hi, i am sorry, but i am a little late 😃, but i saw this question by searching something else. translate() is a very nice function, that allows to replace multiple characters in one run. see my code and some comments:
transltbl = {'a': '1','b': '2','c': '3', 'd':'4'} # defining the pairs source:target.
tr_table = str.maketrans(transltbl) # {97: '1', 98: '2', 99: '3', 100: '4'} # create translate table that is a dict containing ascii values
print('abcd'.translate(tr_table)) # perform translation. you can also do translation to a variable
+ 1
not sure why i had to do it this was but it works:-
print(mystring.translate({ord('a'):ord('1'), ord('b'):ord('2'), ord('c'):ord('3'), ord('d'):ord('4')}))
or this way:-
mystring = 'abcd'
mystring2 = '1234'
mytable = str.maketrans(mystring, mystring2)
print(mytable) # < just to see what happens
print(mystring.translate(mytable))