转换程序

Conversion Program

我有一个程序需要提示用户输入单词和键。接下来,程序应删除单词中的所有空格、标点符号和所有数字,并将所有字母转换为大写。完成后,我需要程序用密钥替换单词的所有字符。所以如果这个词是一个图书馆,并且键是 moose,程序应该打印出 moosemo。我知道这部分包含类似 append.key(len plaintext) 的东西,但我不确定如何。我没有完成很多代码,因为我很迷茫。这是我目前所拥有的:

phrase = input("Please enter the phrase to be encrypted: ")  #prompt user for phrase
encryptionkey = input("Please enter the key: ")   #prompt user for encryption key

print(phrase.upper())  #converts all characters from phrase to uppercase

如果有人知道要做什么或要更改什么,请告诉我。请在回复中显示代码更改。提前致谢

我使用了 here and here 的答案来撰写这篇文章。 这是您可以使用的一种方法,使用字符串 class 去除标点符号和数字。

import string

phrase = input("Please enter the phrase to be encrypted: ")  #prompt user for phrase
encryptionkey = input("Please enter the key: ")   #prompt user for encryption key


#replace - gets rid of spaces
#first translate - gets rid of punctuation
#second translate - gets rid of digits
#upper - capitalizes.

phrase = phrase.replace(" ", "")\
    .translate(str.maketrans('', '', string.punctuation))\
    .translate(str.maketrans('','',string.digits))\
    .upper()


times_to_repeat = len(phrase)//len(encryptionkey)
leftover_length = len(phrase)%len(encryptionkey)

#multiply string by how many times longer it is than the encryption, then add remaining length.

#in python you can do 'string'*2 to get 'stringstring'

final_phrase = encryptionkey*times_to_repeat+encryptionkey[:leftover_length]

print(final_phrase)

输出:

# Only keep the alphabet characters
phrase = ''.join(c for c in phrase if c.isalpha())  
# Add the encryption key at least 1 more times than divisible (to count for remainder)
# and slice the output to the length needed
phrase = (encryptionkey * (1 + len(phrase) // len(encryptionkey)) [:len(phrase)]