Search code examples
pythonencodingdecoding

How to make each letter of a string a variable in python


I'm trying to make a encoder in python

Here is the code so far. It works fine but i want to change each letter in the string to the corresponding number eg: a=1, b=2. so then it would end up as a number sentence. My aim is to have 2 programs, one for encoding and one for decoding

print "Welcome to the encoder"
Letter1 = raw_input ("Please input the first letter of the word: ")
Letter2 = raw_input ("Please input the second letter of the word: ")
Letter3 = raw_input ("Please input the third letter of the word: ")
Letter4 = raw_input ("Please input the fourth letter of the word: ")
Letter5 = raw_input ("Please input the fifth letter of the word: ")
Letter6 = raw_input ("Please input the sixth letter of the word: ")
Letter7 = raw_input ("Please input the seventh letter of the word: ")
Letter8 = raw_input ("Please input the eighth letter of the word: ")
Letter9 = raw_input ("Please input the ninth letter of the word: ")
Letter10 = raw_input ("Please input the tenth letter of the word: ")
Letter11 = raw_input ("Please input the eleventh letter of the word: ")
Letter12 = raw_input ("Please input the twelvth letter of the word: ")
print "Your code is " + Letter3 + Letter2 + Letter1 + Letter6 + Letter5 
+ Letter4 + Letter9 + Letter8 + Letter7 + Letter12 + Letter11 + 
Letter10

Solution

  • You could use a dict (dictionary) to store each letter and its corresponding number. This is flexible if you would like to change the code to something other than than the ordinal of the letter.

    # define the dictionary
    encoder = {"a":"1", "b":"2", "c":"3", "d":"4", "e":"5"}
    
    # take your input
    Letter1 = raw_input ("Please input the first letter of the word: ")
    Letter2 = raw_input ("Please input the first letter of the word: ")
    Letter3 = raw_input ("Please input the first letter of the word: ")
    
    # print out the encoded version
    print encoder[Letter1] + encoder[Letter2] + encoder[Letter3]