Replace characters of a string in python using Lists

2

Good! I try to make my script go through a string and replace each character with another string using lists to be able to change each of the characters in a simpler way, but when going through my list it does not replace them because it limits them the cycle range, is there a function that allows me to replace all the characters in a list with other string or should I put two cycles in the code in the same way?

lock = ("plmnkoijbvhuygcxfteszaqw")
key = ("abcdefghijklmnopqrstuvwxyz")
toWrite = list("eola")

x = 0
y = 0

  for i  in range(len(toWrite)):
    if toWrite[x] == key[y]:
        toWrite[x] = lock[y]
        x = x + 1
    else:
      y = y + 1


print(toWrite)
    
asked by Christian D'Albano 27.11.2017 в 02:22
source

1 answer

1

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)) 
    
answered by 27.11.2017 в 02:40