初学者Python:格式输出

2024-04-25 23:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力完成一项任务,直到遇到这个小问题。在

我的难题是:我的输出正确打印,但如何使键及其各自的输出整齐地打印在一起?在

示例:

  • 关键1:ebcdeb

  • 键2:EFGFHI

我的代码:

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

Tags: thetokeyinfromforoutputmain
3条回答

您应该看看用户指南的Input and Output section。它使用了几种格式化字符串的方法。就个人而言,我仍然使用"old"方法,但是既然您正在学习,我建议您看看"new"方法。在

如果我想用“old”方法漂亮地输出这个结果,我会做print 'Key %3i: %r' % (key, output)。这里的3i表示给一个整数三个空格。在

如果我理解正确,您需要重置output每个循环,并且在每个循环期间print,因此请更改:

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

收件人:

^{pr2}$

旧结果:

Key 25 : MARK NBSL ... KYPI LZQJ

新结果:

Key 0 : MARK 
Key 1 : NBSL 
   #etc
Key 24 : KYPI 
Key 25 : LZQJ 

首先,在print "Key", key, ":", output中,使用+而不是,(这样可以得到正确的字符串连接)。在

您希望key及其对应的output在每个外部for循环迭代中打印。我想我明白为什么现在不发生了。提示:你的print语句现在真的在外循环中吗?在

相关问题 更多 >