简体   繁体   中英

why is my caeser cipher only printing the last letter of string? python

def caesar_cipher(offset, string):
    words = string.replace(" ", " ")
    cipher_chars = "abcdefghijklmnopqrstuvwxyz"
    word_i = 0
    while word_i < len(words): 
        word = words[word_i]

        letter_i = 0 
        while letter_i < len(word): 
            char_i = ord(word[letter_i]) - ord("c")
            new_char_i = (char_i + offset) % 26
            value = chr(new_char_i + ord("c"))
            letter_i += 1
        word_i += 1

    return words.join(value)
print caesar_cipher(3, "abc")

Hey everyone, for some reason my ceasar cipher is only printing the last letter in my string, when I want it to cipher the whole string, for example, if i print an offset of 3 with string "abc" it should print def, but instead is just printing the f. Any help is greatly appreciated!

value is overwritten in the loop. You want to create a list passed to join (ATM you're joining only 1 character):

value = []

then

value.append(chr(new_char_i + ord("c")))

the join statement is also wrong: just do:

return "".join(value)

Note that there are other issues in your code. It seems to intent to process several words, but it doesn't, so a lot of loops don't loop (there's no list of words, it's just a word), so what you are doing could be summarized to (using a simple list comprehension):

def caesar_cipher(offset, string):
    return "".join([chr((ord(letter) - ord("c") + offset) % 26 + ord("c")) for letter in string])

and for a sentence:

print(" ".join([caesar_cipher(3, w) for w in "a full sentence".split()]))

As a nice commenter noted, using c as start letter is not correct since it trashes sentences containing the 3 last letters. There's no reason not to start by a (the result are the same for the rest of the letters):

def caesar_cipher(offset, string):
    return "".join([chr((ord(letter) - ord("a") + offset) % 26 + ord("a")) for letter in string])

Aside: a quick similar algorithm is rot13 . Not really a cipher but it's natively supported:

import codecs
print(codecs.encode("a full sentence","rot13"))

(apply on the encoded string to decode it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM