JES Cipher remove spaces and punctuation

101 Views Asked by At

I have the following code with the output below. I was wondering how I should change the code in order to get an answer where there are no zs in it. In other words, I need it to ignore blanks/spaces and punctuation so that the final output would be sdfqfqeshqs instead.

def buildCipher(key):
 alpha = "abcdefghijklmnopqrstuvwxyz"
 rest = ""
 for letter in alpha:
  if not (letter in key):
   rest = rest + letter
 print key + rest

def encode2(string, alpha2):
 alpha = "abcdefghijklmnopqrstuvwxyz"
 secret = ""
 for letter in string:
  index = alpha.find(letter)
  secret = secret+alpha2[index]
 print secret

buildCipher("earth") results in earthbcdfgijklmnopqsuvwxyz.

encode2('this is a test', "earthbcdfgijklmnopqsuvwxyz") results in sdfqzfqzezshqs

1

There are 1 best solutions below

0
On

alpha.find(letter) returns -1 if letter isn't in alpha. And alpha2[-1] is the last letter in alpha2. So you just need to skip that letter if it has an index of -1. Like this:

def encode2(string, alpha2):
    alpha = "abcdefghijklmnopqrstuvwxyz"
    secret = ""
    for letter in string:
        index = alpha.find(letter)
        if index != -1:
            secret = secret + alpha2[index]
    print secret