5

If I have list='abcdedcba'

and i want: a=z, b=y, c=x, d=w, e=v so it would translate to:

translate='zyxwvwxya'

How would I do this? If I construct a dictionary

>>> d=dict(zip(('a','b','c','d','e'),('z','y','x','w','v')))

and type

>>> example= d[x] for x in list
>>> print translate
['z', 'y', 'x', 'w', 'v', 'w', 'x', 'y', 'z']

How do I get it back into the form

translate='zyxwvwxyz'

?

joce
  • 9,624
  • 19
  • 56
  • 74
O.rka
  • 29,847
  • 68
  • 194
  • 309

6 Answers6

12
the_list = ['z', 'y', 'x', 'w', 'v', 'w', 'x', 'y', 'z']
print "".join(the_list)
eat_a_lemon
  • 3,158
  • 11
  • 34
  • 50
5

For monoalphabetic substitution, use maketrans and translate from the string module. They operate like the unix tr command. Joining with an empty separator is the correct answer for that last step, but not necessary for this exact task.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
2
''.join(translate)

I'm not sure this is what you want?

jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
2

an example of using maketrans and translate:

>>> import string
>>> table = string.maketrans('abcdef', 'zyxwvu')
>>> 'abdedddfdffdabe'.translate(table)
'zywvwwwuwuuwzyv'

Assuming you want to substitute all letters in the ASCII alphabet:

import string
reversed_ascii_letters = string.ascii_letters[::-1]
# reorder lowercase and uppercase
reversed_ascii_letters = reversed_ascii_letters[26:] + reversed_ascii_letters[:26]
table = string.maketrans(string.ascii_letters, reversed_ascii_letters)
data = 'The Quick Brown Fox Jumped Over the Lazy Dog'
print data.translate(table)
gurney alex
  • 13,247
  • 4
  • 43
  • 57
1
>>> import string
>>> table = string.maketrans(string.lowercase, string.lowercase[::-1])
>>> 'abcdedcba'.translate(table)
'zyxwvwxyz'
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
0
>>> import string
>>> letters = string.lowercase
>>> letters
'abcdefghijklmnopqrstuvwxyz'
>>> def revert_string(s):
    s_rev = ''
    for c in s:
        s_rev += letters[len(letters) - 1 - letters.find(c)]
    return s_rev

>>> s = 'zearoizuetlkzjetkl'
>>> revert_string(s)
'avzilrafvgopaqvgpo'
Emmanuel
  • 13,935
  • 12
  • 50
  • 72