0

This is a codecademy challenge, i am trying to offset the letters in the input string in relation to the english alphabet. lets say if we enter d with an offset of 3 it should return a. What am i doing wrong ? I am new to python i started 3 days ago because of the quarantine, love it so far.

import string
a = list(string.ascii_lowercase)

word = "assa"
i = ""
j= ""
x = 0

for j in a:
    for i in word:
        if i == j:
            x = (int(a.index(j)) - 10)
            z = str(a[x])
        sol = word.replace(i,z)


print(sol)
#def cipher(word):


1 Answers1

1

sol = word.replace(i,z)

Every time, this goes back to the original value of word, figures out the result of making the replacement, and gives the name sol to the result. For your general approach to work, you would need to rename the result as word.

When you do this, you should not loop over the characters in word. .replace(i, z) already replaces every appearance of i with z (since i == j, you could equivalently have used j). It is also a bad idea to modify the thing you are looping over.

However, there is a much most straightforward way to implement this entire solution, using str.translate and str.maketrans - see for example.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    For what it's worth the OP is not modifying the thing they are looping over. You can't really do that with immutable strings. – Mark Apr 18 '20 at 01:29
  • I m trying to figure it out without looking at the whole answer, to get the logic of the thing @MarkMeyer – singhsokhal Apr 18 '20 at 01:43