Jr.
Jr.

Reputation: 111

Beginner Python: Format Output

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:

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()

Upvotes: 2

Views: 1011

Answers (3)

Mark Tolonen
Mark Tolonen

Reputation: 177396

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 

Upvotes: 1

Vorticity
Vorticity

Reputation: 4926

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.

Upvotes: 0

musical_coder
musical_coder

Reputation: 3896

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?

Upvotes: 0

Related Questions