如何用其他字母替换字母来创建加密代码?

发布于 2025-01-14 14:53:04 字数 850 浏览 2 评论 0原文

有人告诉我在一个项目中使用 python 创建加密代码,方法是使用字典(ASCII)将字母表中的所有字母替换为其他随机字母。让用户输入一些内容,然后向他显示加密的消息。

我这样做了,但显然没有成功:

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)

当我尝试这段代码并添加越来越多的字母时,它不起作用(例如:我输入“abc”来测试它,而不是在输出中给我“jfn” ,它给了我“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)

输出:

Write a sentence to encrypt: abc
jyn

Process finished with exit code 0

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜尕妞 2025-01-21 14:53:05

您应该注意不要替换已经被替换的字符。

像下面这样的东西可能适合你。

mapping = dict(zip('abc', 'xyz'))
string = 'abacabcd'

''.join(map(lambda char: mapping.get(char, char), string))

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))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文