I've been told in a project to create an encryption code using python, by replacing all the letters in alphabets with other random letters using a dictionary (ASCII). And let the user type something, then show him the encrypted message.
I did this but apparently it didn't work out:
string = input("Write a sentence to encrypt: ")
print(string.replace("a", "j"))
print(string.replace("b", "f"))
print(string.replace("c", "n"))
print(string.replace("d", "t"))
print(string.replace)
When I tried this code and added more and more letters, it didn't work (example: I typed "abc" to test it and instead of giving me "jfn" in output, it gives me "jyn").
string = input("Write a sentence to encrypt: ")
string = string.replace("a", "j")
string = string.replace("b", "f")
string = string.replace("c", "n")
string = string.replace("d", "t")
string = string.replace("e", "g")
string = string.replace("f", "y")
string = string.replace("g", "i")
print(string)
Output:
Write a sentence to encrypt: abc
jyn
Process finished with exit code 0
CodePudding user response:
The str.replace function doesn't update the string in-place, it actually returns a copy. You need to keep that copy, otherwise you don't keep the modifications.
Your last print also prints the function, as opposed to the string.
Try something like
string = input("Write a sentence to encrypt: ")
string = string.replace("a", "j")
string = string.replace("b", "f")
string = string.replace("c", "n")
string = string.replace("d", "t")
print(string)
CodePudding user response:
You should take care of not replacing characters that have already been replaced.
Something like the following could work for you.
mapping = dict(zip('abc', 'xyz'))
string = 'abacabcd'
''.join(map(lambda char: mapping.get(char, char), string))