我试图完成任务,直到我遇到这个小问题。
我的困境是:我的输出打印正确,但如何将#键及其各自的输出整齐地打印出来?
密钥1:ABCDEB
密钥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()
答案 0 :(得分:1)
如果我理解正确,您需要在每个循环中重置output
每个循环和print
,因此请更改:
output = ""
for key in range(0,26):
## Other stuff
print "Key", key, ":", output
为:
for key in range(0,26):
output = ""
## Other stuff
print "Key", key, ":", output
旧结果:
Key 25 : MARK NBSL ... KYPI LZQJ
新结果:
Key 0 : MARK
Key 1 : NBSL
#etc
Key 24 : KYPI
Key 25 : LZQJ
答案 1 :(得分:0)
首先,在print "Key", key, ":", output
中,使用+
代替,
(以便获得正确的字符串连接)。
您希望key
及其对应的output
与每个外部for
循环迭代一起打印。我想我明白为什么现在还没发生。提示:你的print
声明现在实际上属于外循环吗?
答案 2 :(得分:0)
您应该查看用户指南的Input and Output section。它通过几种格式化字符串的方法。就个人而言,我仍然使用"old"方法,但是既然你正在学习我建议你看一下"new"方法。
如果我想用“旧”方法巧妙地输出这个,我会做print 'Key %3i: %r' % (key, output)
。这里3i
表示给一个整数提供三个空格。