0

I have a program where I need to prompt the user for an input of a word and a key. Next, the program should remove all the spaces, punctuation and all numbers from the word and convert all the letters into uppercase. Once that is done I need the program to replace all the characters of the word with the key. So if the word is a library, and the key is moose, the program should print out moosemo. I know that this part includes something like append.key(len plaintext) something of this fashion, but I'm not exactly sure how. I don't have a lot of the code done because I am pretty lost. Here is what I have so far:

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

If anyone knows what to do or what to change, please let me know. Please show the change in code with your response. Thanks in advance

2 Answers2

1

I used answers from here and here to make compose this. Here is one way you might do it, using the string class to get rid of punctuation and numbers.

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)

Output: enter image description here

Richard K Yu
  • 2,152
  • 3
  • 8
  • 21
  • Hi thanks for your comment. Could you explain why the backward slashes are there after the phrase and translate lines? – Hypnotix999 Jan 20 '22 at 16:12
  • @MaciekB This is just to make the code more readable, it allows me to put the code of one line on multiple lines. You can delete all the backward slashes and put it all on one line if that is your preference. – Richard K Yu Jan 20 '22 at 16:19
1
# 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)] 
MYousefi
  • 978
  • 1
  • 5
  • 10