The string key
and luck
must have the same number of elements, since each value of key
has to be exchanged for the corresponding% of luck
.
Correcting the above (I have added "d" and "r" to string lock
), you can use str.translate
for what you want, creating a table with the replacements using str.maketrans
:
lock = "plmnkoijbvhuygcxfteszaqwdr"
key = "abcdefghijklmnopqrstuvwxyz"
trantab = str.maketrans(key, lock)
toWrite = "eola"
print(toWrite.translate(trantab))
If for some reason you do not want to use str.translate
a good option is to use a dictionary to create the translation table, it will be much more efficient than using indexing:
lock = "plmnkoijbvhuygcxfteszaqwdr"
key = "abcdefghijklmnopqrstuvwxyz"
toWrite = "eola"
trantab = {key: value for key, value in zip(key, lock)}
toWrite = "".join(trantab.get(c, c) for c in toWrite)
print(toWrite)
transtab
in this case is a dictionary of the form:
{'a': 'p', 'b': 'l', 'c': 'm', ...}
For each key (character to be replaced) we have a value (character that substitutes). The dict.get
method returns the value of each key passed as the first argument, if the key does not exist in the dictionary it returns what we pass as the second element (in this case the character of the original string).
In both cases the translation tables are reusable, which is important if you are going to apply it on multiple chains.
The output is:
kcup
I've been budgeting that you use Python 3 since you do not use the tag for Python 2, however if you want to use translate
in Python 2 we just import
maketrans
of the library string
:
from string import maketrans
lock = "plmnkoijbvhuygcxfteszaqwdr"
key = "abcdefghijklmnopqrstuvwxyz"
trantab = maketrans(key, lock)
toWrite = "eola"
print(toWrite.translate(trantab))