0

I am new to python and am stuck on the task below. Below is an example of my input file and what I want it to output.

Input File Message (from online sample)

So pure of heart
And strong of mind
So true of aim with his marshmallow laser
Marshmallow laser

Output File Message

LhtinkXthYtaXTkm
ugWtlmkhgZthYtfbgW
LhtmknXthYtTbftpbmatabltfTklafTeehpteTlXk
FTklafTeehpteTlXk

Below is my syntax and guidance as to why it isn't completing the task intended would be helpful. It is printing 'wwww'....I believe it is a 'w' for each line.

inputFileName = input("Enter the message to encrypt: ")
key = int( input("Enter the shift key: " ))
outputFileName = input("Enter the output file name: " )

infile=open(inputFileName,"r")
outfile = open( outputFileName, "w" )

sequence=infile.readlines()

alphabet = " ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
shiftedAlphabetStart = alphabet[len(alphabet) - key:]
shiftedAlphabetEnd = alphabet[:len(alphabet) - key]
shiftedAlphabet = shiftedAlphabetStart + shiftedAlphabetEnd


print( alphabet )
print( shiftedAlphabet )

encryptedMessage = ''
for character in sequence:
    letterIndex = alphabet.find( character )
    encryptedCharacter = shiftedAlphabet[letterIndex]
    #print( "{0} -> {1}".format( character, encryptedCharacter ) )

    encryptedMessage = encryptedMessage + encryptedCharacter

print( "The encrypted message is: {0}".format( encryptedMessage ))
1
  • 1
    Note: you can just use string.ascii_letters instead of writing the whole alphabet Commented May 28, 2018 at 0:49

1 Answer 1

1

If you print(sequence), you'll realize that it's a List of lines, not a string.

So when you iterate through it with for character in sequence:, you're not iterating through the original text character by character, you're iterating through the list line by line.

This is because readlines() return a list of lines.

You can, if you still want to use readlines(), try adding something like:

original_text = ''

for line in sequence:
    original_text += line

A better way however, is to simply change sequence = infile.readlines() to sequence = infile.read().

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, all comments were helpful. This fixed my issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.