Reputation: 5
I'm trying to make an encrypter, where it shifts the letter 3 times (so A becomes D, B becomes E, etc.) Then X goes back to A, Y to B, and Z to C. I'm using ASCII values to shift them. I'm trying to see if any part of the list has the ASCII values of X, Y, or Z, then if yes, change that element back to A, B, or C's ASCII value. I know you can check if there is a value in a list, but how do I actually take this value and change it? Here is what I'm trying to do:
def encrypt(userInput):
#Find Ascii Value of plaintext
asciiValue = [ord(c) for c in userInput]
#Convert Ascii value (list) into integers
intAscii = [int(x) for x in asciiValue]
encryptedAscii = [n + 3 for n in intAscii]
if '120' in encryptedAscii:
encryptedAscii = '97'
elif '121' in encryptedAscii:
encryptedAscii = '98'
elif '122' in encryptedAscii:
encryptedAscii = '99'
else:
encryptedOutput = ''.join(chr(v) for v in encryptedAscii)
return encryptedOutput
Thanks!
Upvotes: 0
Views: 64
Reputation: 51683
Using ord
and chr
is fine, but there is also an easier method: str.maketrans and str.translate:
from string import ascii_uppercase as ABC, ascii_lowercase as abc
def encrypt(text, tr):
return text.translate(tr)
# join translation dicts for ABCD and abcs to
# create mapping from 2 strings of equal lenght,
# first is "from" second is "to" mapping:
tr = {**str.maketrans(abc, abc[3:]+abc[:3]), # lower case a-z
**str.maketrans(ABC, ABC[3:]+ABC[:3])} # upper case A-Z
text = "ABCDEFGXYZabcdefgxyz"
print(text, " => ", encrypt(text,tr))
Output:
ABCDEFGXYZabcdefgxyz => DEFGHIJABCdefghijabc
Upvotes: 0
Reputation: 6056
You actually don't need to check for x, y, z
separately. Just use the modulo operator (%
) so if it overflows, it will turn back to a, b, c
:
def encrypt(userInput):
# Find Ascii Value of plaintext
asciiValue = [ord(c) for c in userInput]
# Convert Ascii value (list) into integers
intAscii = [int(x) - 97 for x in asciiValue]
encryptedAscii = [(n + 3) % 26 + 97 for n in intAscii]
encryptedOutput = ''.join(chr(v) for v in encryptedAscii)
return encryptedOutput
from string import ascii_lowercase
print(encrypt(ascii_lowercase))
Output:
defghijklmnopqrstuvwxyabc
Upvotes: 1