It is an exercise in one of the Python courses. I don’t understand why this doesn’t work.
Caesar ciphers work by giving you an enconded message and a key, which is the number of times you have to shift the letter to find the correct one. In this case the key is 10.
The error i get when running this is for alphabet[index]:
IndexError: string index out of range
alphabet = "abcdefghijklmnopqrstuvwxyz"
message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj"
new_message = ""
for character in message:
if character in alphabet:
index = alphabet.find(character)
index = index + 10
if index > len(alphabet):
index = index - len(alphabet)
new_message = new_message + alphabet[index]
else:
new_message = new_message + character
print(new_message)
I’m lazy, so I just popped in some debug code:
alphabet = "abcdefghijklmnopqrstuvwxyz"
message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj"
new_message = ""
for character in message:
if character in alphabet:
print("character", character)
index = alphabet.find(character)
print("found", index)
index = index + 10
print("shift", index)
if index > len(alphabet):
index = index - len(alphabet)
print("shift 2", index)
new_message = new_message + alphabet[index]
else:
new_message = new_message + character
print(new_message)
Final fail:
character i
found 8
shift 18
character q
found 16
shift 26
Traceback (most recent call last):
File "t.py", line 15, in <module>
new_message = new_message + alphabet[index]
IndexError: string index out of range
Well, 26 is a wee bit over… try if index >= len(alphabet):
thanks! i also found i was supposed to use modulus 26, which works but i’m not sure how. my way was more… artisanal
Actually, I was going to mention the mod thing. To give an idea, this
print([x % 3 for x in (0,1,2,3,4,5,6)])
Yields:
[0, 1, 2, 0, 1, 2, 0]
Note the because find returns a -1
index on fail, you needn’t bother with the in
check.
I took a stab at this and came up with:
def ceasar(msg, shift = 3, domain = "abcdefghijklmnopqrstuvwxyz"):
def enc_char(c):
index = domain.find(c)
if index == -1:
return c
return domain[(index + shift) % len(domain)]
return "".join(enc_char(c) for c in msg)
message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj"
print(ceasar(message, 10))