Help with this code (Caesar Cipher) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Help with this code (Caesar Cipher)

I'm trying to create a Caesar Cipher converter. So far what I got is: https://code.sololearn.com/cxcoqoY9UNuo/?ref=app This code works partially, because when the new index (alphabet index + shift) is higher than the alphabet lenght the program crashes. Also when the partial cipher is equal to one of the following letters to be converted it ends up converting all of them. (in hello, for example, when shift is equal to 3, both L are changed to O, and when the O changes to R, It ends up changing all 3 Os)

1st Feb 2018, 2:54 AM
Antônio Gabriel Zeni Landim
Antônio Gabriel Zeni Landim - avatar
3 Answers
+ 5
Theres an operation that will make a number wrap back to 0 after it hits a limit and it's called modulo! (index + shift) % 26 will do exactly what you want. If the shifted index happens to be 28, it will become 28 - 26 == 2 instead. To get rid of the multiple replacements thing, try putting the shifted character into a new string. You loop through the user input and append the shifted char to an output string instead of doing a replace. That way you keep things seperate and there's no mixing caesar shifted text with the plaintext!
1st Feb 2018, 3:16 AM
Schindlabua
Schindlabua - avatar
+ 2
also, I don't know what to do about spaces. At first I thought the program would ignore the fact that there's no " " in the alphabet list and just not execute the replace method, but it crashes. Just had an idea: could I solve with some if/elif/else inside the for loop?
1st Feb 2018, 2:58 AM
Antônio Gabriel Zeni Landim
Antônio Gabriel Zeni Landim - avatar
+ 1
You can make a function that only replaces one character. Then you call if for each character in your text, IF the character is a letter (use string.isalpha()).
2nd Feb 2018, 4:01 PM
Pedro Demingos
Pedro Demingos - avatar