I have a cryptography project and want to decrypt sentences using python. I wrote this code but can't get an output, where the words have spaces between them.
def vigenere_decrypt(key: str, text: str) -> str:
decrypted_text = ""
encrypted_text = text.replace(" ", "")
key_length = len(key)
for i, char in enumerate(encrypted_text): #ex. 0 y, 1 a...
key_char = key[i % key_length] # ex. key = KEY, text = MESSAGE => KEYKEYK
shifted_char = (ord(char) - (ord(key_char))) % 26
for c in text:
if c in text == " ":
decrypted_char = " "
else:
decrypted_char = chr((shifted_char) + ord('a'))
decrypted_text += decrypted_char
return decrypted_text
raise NotImplementedError()
print(vigenere_decrypt("math", "yadl ut ahbpxu") )
I guess my for c in text block doesn't work and don't know why. I would be really happy if you could help me.
if c in text == " "
is not doing what you want. It's checking if the value ofc in text
, which can be eitherTrue
orFalse
, is equal to the string" "
, which will never be possible, and therefore a space character will never be outputted. It almost certainly seems like the only code you need for that line isif c == " "
.