我一直在努力完成一项任务,直到遇到这个小问题。在
我的难题是:我的输出正确打印,但如何使键及其各自的输出整齐地打印在一起?在
关键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()
您应该看看用户指南的Input and Output section。它使用了几种格式化字符串的方法。就个人而言,我仍然使用"old"方法,但是既然您正在学习,我建议您看看"new"方法。在
如果我想用“old”方法漂亮地输出这个结果,我会做
print 'Key %3i: %r' % (key, output)
。这里的3i
表示给一个整数三个空格。在如果我理解正确,您需要重置
output
每个循环,并且在每个循环期间print
,因此请更改:收件人:
^{pr2}$旧结果:
新结果:
首先,在
print "Key", key, ":", output
中,使用+
而不是,
(这样可以得到正确的字符串连接)。在您希望
key
及其对应的output
在每个外部for
循环迭代中打印。我想我明白为什么现在不发生了。提示:你的print
语句现在真的在外循环中吗?在相关问题 更多 >
编程相关推荐