Search code examples
pythoncaesar-cipher

Ceasar's cipher in python


i'm making a simple program for translating text with Ceasar's cipher. Here is my code.

alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
text = "hello how are you"
text = text.split(" ")
new_text_array = []
key = 3
for w in range(len(text)):
    new_word_array = []
    word = list(text[w])
    for i in range(len(word)):
        if word[i] in alphabet:
            new_index = alphabet.index(word[i]) + key
            if new_index > 25:
                new_index -= 26
            new_word_array += alphabet[new_index]
    new_word = ''.join(new_word_array)
    print(new_word)
    new_text_array += new_word
    print(new_text_array)
new_text = ' '.join(new_text_array)
print(new_text)

When i run the code, on line 20, it correctly prints ciphered word as a string, but on line 21, where i'm adding words to array, it adds each letter as an individual item in array instead of adding whole word. I'm still fairly new to python, what am i missing? Please help. Sorry for my english, hope you'll understand what i'm trying to say.


Solution

  • You need to use new_text_array.append(new_word).

    In new_text_array += new_word the += means that you are adding all elements of the second array to the first array, so the Python iterates over new_word, because string can also be iterated over with new_word[x], and adds all its elements (letters here) as separate elements.

    Another option here is new_text_array += [new_word], where you just put new_word into the array as the only element