Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Cesar Cipher
#2
Some tips and as example print both with and without spaces.
Also range(len(chain_to_code)) is not good here,just remember that range(len(sequence)) is almost always a bad way.
So just iterate over the string,no adding on is needed.
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
GAP = 4
chain_to_code = "ave caesar"
encoded_without_spaces = ""
encoded_with_spaces = ""

for character in chain_to_code:
    #print(repr(character)) # Tips to see all
    if character in ALPHABET:
        encoded_char = ALPHABET[(ALPHABET.index(character) + GAP) % len(ALPHABET)]
        encoded_without_spaces += encoded_char
        encoded_with_spaces += encoded_char
    # Handle spaces
    elif character == " ":
        encoded_with_spaces += " "

print(f"Encoded without spaces: {encoded_without_spaces}")
print(f"Encoded with spaces: {encoded_with_spaces}")
Output:
Encoded without spaces: ezigeiwev Encoded with spaces: ezi geiwev
But just need this as it will handle inputs string with or without space correct.
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
GAP = 4
chain_to_code = "ave caesar"
concatenated_chain = ""

concatenated_chain_with_spaces = ""
for character in chain_to_code:
    if character in ALPHABET:
        concatenated_chain += ALPHABET[(ALPHABET.index(character) + GAP) % len(ALPHABET)]
    else:
        concatenated_chain += character

print(f"Encoded: {concatenated_chain}")
Output:
Encoded: ezi geiwev
Reply


Messages In This Thread
Cesar Cipher - by ForsakenDusk - Mar-31-2024, 09:40 AM
RE: Cesar Cipher - by snippsat - Mar-31-2024, 11:59 AM
RE: Cesar Cipher - by ForsakenDusk - Mar-31-2024, 04:45 PM
RE: Cesar Cipher - by deanhystad - Mar-31-2024, 10:31 PM
RE: Cesar Cipher - by ForsakenDusk - Apr-07-2024, 01:26 PM
RE: Cesar Cipher - by Pedroski55 - Apr-07-2024, 04:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question Rsa Cipher Paragoon2 3 697 Nov-27-2023, 12:30 PM
Last Post: snippsat
  RSA Cipher with blocks Paragoon2 0 542 Nov-26-2023, 04:35 PM
Last Post: Paragoon2
  Caesar Cipher Help pbrowne 2 2,221 Jun-30-2021, 02:36 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020