Vigenèrecipher:如何使加密消息出现在打印功能中?

时间:2018-01-17 22:48:18

标签: python encryption python-3.6 vigenere

我是编码和Python的初学者。现在我正在研究Vigenère cipher

我已经足够用密钥加密消息了。我在每段代码中添加了注释以供参考。这是我的代码。我的问题是在代码之下。

# Ask user for message
print('type a message.')
message = input()

# print a white line for neatness
print()

# ask user for a key
print('give your key')
key = input()

# create a range with the length of the message
ran = range(len(message))

# Iterate though the range and therefor show all the letters
for i in ran:
    # get current letters for this iteration
    currentLetter = message[i]
    currentKeyLetter = key[i % len(key)]

    # Get corresponding numbers
    numberLetter = ord(currentLetter)
    numberKeyLetter = ord(currentKeyLetter)

    # Add two letters
    sumTwoLetters = numberLetter + numberKeyLetter

    # Get the number of the encrypted letter
    newNumberLetter = sumTwoLetters % 128
    # Get the encrypted number based on number
    newLetter = chr(newNumberLetter)

    # print out the result
    printText = currentLetter + "(" + str(numberLetter) + ") + "
    printText += currentKeyLetter + "(" + str(numberKeyLetter) + ") = "
    printText += newLetter + "(" + str(newNumberLetter) + ")"
    print(printText)

代码要求用户输入消息和密钥。 ran变量创建一个带有消息长度的范围。

之后,for循环使用ordchr

使用密钥对邮件进行加密

加密的字母存储在变量newLetter中 用户可以通过printText

查看该程序的功能

但是,我的问题是:如何使加密文本显示在单个字符串上。我试着在循环中做到这一点。我悲惨地失败了(以至于我不想表现出来)

是否有人就如何使加密邮件显示在一行文字中有任何建议?

2 个答案:

答案 0 :(得分:0)

您可以在list循环之后将结果收集到join(),然后将for全部收集到一个字符串中。请参阅有关更改的注释。

...
results = []  # ADDED.

# Iterate though the range and therefor show all the letters
for i in ran:
    # get current letters for this iteration
    currentLetter = message[i]
    currentKeyLetter = key[i % len(key)]

    # Get corresponding numbers
    numberLetter = ord(currentLetter)
    numberKeyLetter = ord(currentKeyLetter)

    # Add two letters
    sumTwoLetters = numberLetter + numberKeyLetter

    # Get the number of the encrypted letter
    newNumberLetter = sumTwoLetters % 128
    # Get the encrypted number based on number
    newLetter = chr(newNumberLetter)

    # print out the result
    printText = currentLetter + "(" + str(numberLetter) + ") + "
    printText += currentKeyLetter + "(" + str(numberKeyLetter) + ") = "
    printText += newLetter + "(" + str(newNumberLetter) + ")"
    results.append(printText)  # PUT IN results LIST INSTEAD OF PRINTING.

print(''.join(results))  # ADDED.

答案 1 :(得分:0)

有两种简单的方法。要么(1)在循环内部构建字符串并将其打印在循环外部,要么(2)在循环中打印每个字符但没有换行符,在循环后加一个换行符。

尝试其中一种方法,如果您需要更多帮助,请添加评论。您将通过自己尝试来了解更多信息!