2

I was trying to finish an assignment until I reached this small issue.

My dilemma is: My output is printed correctly, but how do I get the key # and its respective output to be printed together neatly?

Example:

  • key 1: ABCDEB

  • key 2: EFGFHI

  • etc

My Code:

def main():

    # hardcode
    phrase = raw_input ("Enter the phrase you would like to decode: ")

    # 1-26 alphabets (+3: A->D)
    # A starts at 65, and we want the ordinals to be from 0-25

    # everything must be in uppercase
    phrase = phrase.upper()

    # this makes up a list of the words in the phrase
    splitWords = phrase.split()

    output = ""


    for key in range(0,26):        

        # this function will split each word from the phrase
        for ch in splitWords:

            # split the words furthur into letters
            for x in ch:
                number = ((ord(x)-65) + key) % 26
                letter = (chr(number+65))

                # update accumulator variable
                output = output + letter

            # add a space after the word
            output = output + " "

    print "Key", key, ":", output

 main()
1
  • Well first off your indentation for the print statement is off. Unless that's from copying into SO. Secondly, you can do this: print "Key " + key + ": " + output + "\n", notice the spaces and newline added. Commented Sep 28, 2013 at 1:03

3 Answers 3

1

If I understand you correctly, you need to reset output each loop, and print during each loop, so change:

output = ""
for key in range(0,26):        
    ## Other stuff
print "Key", key, ":", output

to:

for key in range(0,26):        
    output = ""
    ## Other stuff
    print "Key", key, ":", output

Old result:

Key 25 : MARK NBSL ... KYPI LZQJ

New result:

Key 0 : MARK 
Key 1 : NBSL 
   #etc
Key 24 : KYPI 
Key 25 : LZQJ 
Sign up to request clarification or add additional context in comments.

Comments

0

First, in print "Key", key, ":", output, use + instead of , (so that you get proper string concatenation).

You want key and its corresponding output to print with every outer for loop iteration. I think I see why it's not happening at the moment. Hint: is your print statement actually falling under the outer loop right now?

Comments

0

You should take a look at the Input and Output section of the users guide. It goes through several methods of formatting strings. Personally, I use the "old" method still, but since you are learning I would suggest taking a look at the "new" method.

If I wanted to output this prettily with the "old" method, I would do print 'Key %3i: %r' % (key, output). Here the 3i indicates to give three spaces to an integer.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.