Cazards
Cazards

Reputation: 25

how to get python to recognize more than one letter at a time

So my current assignment is to make a cipher using a double encoding. So I have one variable that is a list of letters aa to zz. Another variable is a copy of that same list shuffled. I then inserted the Alpha pair as the key in a dictionary and the pair copy as the value in the dictionary. The issue I have run into now is getting it to look at one more than one letter in the message at a time.

I tried just creating a new variable and a for loop to simply run through it but it is only looking at one letter at a time


import random

alpha= 'abcdefghijklmnopqrstuvwxyz '
alphalist= list(alpha)
alphapair= []

for let1 in alphalist:
    for let2 in alphalist:
        pair = let1+let2
        alphapair.append(pair)

paircopy= alphapair[:]

random.seed(6767)
random.shuffle(paircopy)

incoding_cipher=dict(zip(alphapair,paircopy))

message=input("Please type the message you would like to encode: ") #optional to allow for an input to encode
message= message.lower()
incoded_message=''

for let in message:
    incoded_message += incoding_cipher[let]

print(incoded_message)

Upvotes: 1

Views: 316

Answers (2)

Tom Lynch
Tom Lynch

Reputation: 913

Change:

for let in message:
    incoded_message += incoding_cipher[let]

to:

for first, second in zip(message[::2], message[1::2] + ' ' * (len(message) % 2)):
    key = first + second
    incoded_message += incoding_cipher[key]

Upvotes: 0

CryptoFool
CryptoFool

Reputation: 23119

Something like this will work for you:

msgtemp = (message + ' ') if (len(message) % 2) else message
for i in range(0, len(msgtemp), 2):
    pair = msgtemp[i] + msgtemp[i + 1]
    incoded_message += incoding_cipher[pair]

This adds a space to the end of the message if it is of odd length.

Upvotes: 1

Related Questions