I am trying to make a simple cryptography program using a simple subsitution method. If any one could help that would be nice. I need to be able to encode it as well as decode it. but im just a little confused on how to go about doing that.

here is the code so far.

""" crypto.py
    Implements a simple substitution cypher


def main():
  keepGoing = True
  while keepGoing:
    response = menu()
    if response == "1":
      plain = raw_input("text to be encoded: ")
      print encode(plain)
    elif response == "2":
      coded = raw_input("code to be decyphered: ")
      print decode(coded)
    elif response == "0":
      print "Thanks for doing secret spy stuff with me."
      keepGoing = False
      print "I don't know what you want to do..."
3 Years
Discussion Span
Last Post by Lucaci Andrew
from string import maketrans
encode=lambda x: x.translate(maketrans(key,alpha))
decode=lambda x: x.translate(maketrans(alpha,key))

It only translates the characters you give in. So lowercase chars are not encoded and decoded.

If you on python3 than it wont work.

Edited by slate: python3


You could use a dictionary, on which you map every character from your alphabet with the key character:

def cryptography(text):
    alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .,;'\"\\[]{}=-+*\|:<>?"
    key = "XPMGTDHLYONZBWEARKJUFSCIQVxpmgtdhlyonzbwearkjufsciqv .,;'\"\\[]{}=-+*\|:<>?"
    crypt, decrypt = {}, {} #dictionaries for crypting and decrypting
    for i, j in zip(alpha, key): crypt[i], decrypt[j] = j, i #fill up the dictionaries
    crypted = ''.join(crypt.get(i) for i in text) #encrypt text
    decrypted = ''.join(decrypt.get(i) for i in crypted) #decrypt text
    print crypted 
    print decrypted

And here's a generic example:

def main():
    text = "Aladdin had a ginny."


which would output this:

Xzxggyw lxg x hywwq.
Aladdin had a ginny.

But again, I don't know if this is what you thought to.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.