12:52 pm - EncoDecode: Encode and Decode a String in Python I created this program for a person I am tutoring. He wanted to know how Python could take a string and convert it to a secret code. I also made it possible to read the code and show a string.
Later we are going to read and write to files. As of now, this is our code. # filename: encoDecode.py # purpose: encode/decode a string from/to a code # author: tdrusk
# import sys is necessary for printing on same line without a space, as a ',' would do. import sys
# Create a list of letters to convert to/from. let = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', '.', ',', ':']
# Create a list of numbers to convert to/from. num = ['1','2','3','4','5','6','7','8','9','~','!','@','#','$','%','^','&','*','(',')','-','=','+','Q','W','E','R', 'T', 'Y', 'U']
# The encode function uses the start object. # The for loop uses the length of start as the amount of times it will iterate. # start[y] is what is in the y spot of the start list. # let.index(start[y]) is the index of the string, start[y], in the let list. # num[let.index(start[y])] uses the index in the let list and passes it to the num list. # For example, start[y] = a. The let.index of start[y] is 1. 1 is then put in num[1], which declares finish as '1'. # sys.stdout.write(finish) prints the individual strings without a space or newline after them. def encode(start): for y in range(len(start)): finish = num[let.index(start[y])] sys.stdout.write(finish)
# The decode function uses the start object # The for loop uses the length of start as the amount of times it will iterate. # start[y] is what is in the y spot of the list. # num.index(start[y]) is the index of the string, start[y], in the num list. # let[num.index(start[y])] uses the index in the num list and passes it to the let list. # For example, start[y] = 1. The num.index of start[y] is 1. 1 is then put in let[1], which declares finish as 'a'. # sys.stdout.write(finish) prints the individual strings without a space or newline after them. def decode(start): for y in range(len(start)): finish = let[num.index(start[y])] sys.stdout.write(finish)
# The Main function ties the necessary functions together def main(): print '\n\t\t\tEncoDecode' ed = str(raw_input('Encode or Decode?(e/d)\n>')) if ed in 'e': start = str(raw_input("Enter the text you want to encode\n>")) # list(start) creates a list of the string previously input. start = list(start) encode(start)
if ed in 'd': start = str(raw_input("Enter the code you want to decode\n>")) # list(start) creates a list of the string previously input. list(start) # Execute decode function decode(start)
# Run main function. main()
This program gave me a better understanding of Python's lists and how I can work with them. Current Mood: pleased Current Music: Dream Theater - Black Clouds & Silver Linings - "A Rite of Passage"
|