简体   繁体   English

我该如何只打印最后一个值?

[英]How do I make this only print the last value?

I have the fallowing code to encrypt a massage: 我有下面的代码来加密消息:

massage= raw_input("Enter message to be encrypted: ")

spec = chr(0b1010101)

key = ord(spec)

encrypt = ""

for i in range(0, len(massage)):

        encrypt = encrypt + chr(ord(massage[i]) ^ key)

        print encrypt

say I give "yo yo" to it 说我给它“哟哟”

it will give me : 它会给我:

,

,: ,:

,:u ,:U

,:u, ,:U,

,:u,: ,:U,:

I only need the final answer which is the ,:u,: 我只需要最后一个答案,即:: u ,:

what do i have to do? 我需要做什么?

Put the print statement outside the loop . 将print语句置于循环之外

Since the print statement is inside, it is running once per iteration. 由于print语句位于内部,因此每个迭代运行一次。 If it is outside, then it will only do it one time-- once it has finished. 如果它在外面,那么它只会做一次-完成后。

for i in range(0, len(massage)):
    encrypt = encrypt + chr(ord(massage[i]) ^ key)

print encrypt

unindent the call to print. 取消打印调用的缩进。 This will take it out of the for loop and only print its value when the loop is finished. 这将使它脱离for循环,并且仅在循环完成时才打印其值。

On a slightly different note, you might want to work on your acceptance rate if you want people to put time and effort into answering your questions. 略有不同的是,如果您希望人们花费时间和精力来回答您的问题,那么您可能希望按接受率进行工作。 You've asked 8 questions so far and you haven't accepted an answer to any of them. 到目前为止,您已经提出了8个问题,但尚未接受任何问题的答案。 (Click the arrow next to an answer to accept it) (单击答案旁边的箭头以接受它)

message= raw_input("Enter message to be encrypted: ")

spec = chr(0b1010101)

key = ord(spec)

encrypt = ""

for i in range(0, len(message)):

    encrypt = encrypt + chr(ord(message[i]) ^ key)

print encrypt

Move the print statement outside the for loop. 将打印语句移到for循环之外。 To do that you need to unindent the print statement. 为此,您需要取消缩进打印语句。

Using a generator: 使用生成器:

message= raw_input("Enter message to be encrypted: ")
key=0b1010101
print ''.join(chr(key^ord(c)) for c in message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM