[英]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? 我的难题是:我的输出正确打印,但是如何使键#及其相应的输出整齐地打印在一起?
key 1: ABCDEB 关键1:ABCDEB
key 2: EFGFHI 关键2:EFGFHI
etc 等等
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()
If I understand you correctly, you need to reset output
each loop, and print
during each loop, so change: 如果我对您的理解正确,则需要在每个循环中重置
output
,并在每个循环中进行print
,因此请更改:
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
First, in print "Key", key, ":", output
, use +
instead of ,
(so that you get proper string concatenation). 首先,在
print "Key", key, ":", output
,使用+
代替,
(以便获得正确的字符串连接)。
You want key
and its corresponding output
to print with every outer for
loop iteration. 您希望
key
及其对应的output
与每个外部for
循环迭代一起打印。 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? 提示:您的
print
语句现在是否真的落在外部循环之下?
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)
. 如果我想使用“旧”方法输出此内容,我会
print 'Key %3i: %r' % (key, output)
。 Here the 3i
indicates to give three spaces to an integer. 此处
3i
表示给整数三个空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.