Skip to content

My letter substitution cipher shows an error whenever there is a space in the input/phrase,to be encoded, how can i fix this?

So, this letter substitution cipher shows an error whenever there is a space (whitespace) in the input/phrase,to be encoded.

Here is my code: Im quite new to python so it would be helpful for any suggestions whatsoever.

from string import ascii_lowercase
import random
EXAMPLE_KEY = ''.join(sorted(ascii_lowercase, key=lambda _:random.random()))
def encode(plaintext, key):
    return ''.join(key[ascii_lowercase.index(char)] for char in plaintext)
def decode(plaintext, key):
    return ''.join(ascii_lowercase[key.index(char)] for char in plaintext)
original = input("PLease enter a phrase: ")
encoded = encode(original, EXAMPLE_KEY)
decoded = decode(encoded, EXAMPLE_KEY)
print("The original is:", original)
print("Encoding it with the key:", EXAMPLE_KEY)
print("Gives:", encoded)
print("Decoding it by the same key gives:", decoded)

Note this isn’t a Caesar Cipher, simply randomly changing the letters to other letters. Thank you

Answer

ascii_lowercase does not contain a space, so ascii_lowercase.index(char) is a ValueError.

One reasonable approach is to just catch this error and return the same character. That would require breaking your join call out into a loop. You could shoehorn an if char in ascii_lowercase into there to keep it in one line, but that would be pretty ugly.

EDIT: like this

def encode(plaintext, key):
  ret = ''
  for char in plaintext:
     try:
       ret += key[ascii_lowercase.index(char)]
     except ValueError:
       ret += char
  return ret