Replacing letters of a string by implementing rotational cipher goes wrong

There is still some things to do to complete the script. But I’m going step by step and got stuck on my way.

# On the way to complete a function for the "Caesar cipher"

import string

def rotate(text: str, key: int):

    # Creating a list of a-z (lc)
    lc = list(string.ascii_lowercase)

    # Creating a new list of a-z (new_lc) with shifted positions
    # for the characters of "lc" according to the argument passed in parameter "key"
    new_lc = []
    for i in range(26):
        i = i + key
        if i > 25:
            i = i - 26

    for char in text:
        if char.isalpha() and char.islower():

            # Replacing each character of "text" by shifting the letter for the value of the "key"
            text = text.replace(char, new_lc[lc.index(char)])

    return text

print(rotate("a e t", 7))
print(rotate("e t a", 7))

The output is:

h l a
l h h

I was expecting the second one to be l a h but for some reason (which I don’t understand) it doesn’t replace t with a in this case like it did in the first one. Looks like in this case, its replacing t with a and then that a with h (repeating the replacing for one letter) which is confusing.
I found the script is working fine with some random strings like “hi there”, “kill” but not working with some others like, “kill the cockroach”. I Can’t understand the problem.
Any help to make me understand and provide a standard solution is appreciated. :smiley:
Thanks for reading this far. :blush:

text is mutating while the loop runs because of text = text.replace(char, new_lc[lc.index(char)])
Thus you are mapping characters more than once.

1 Like