gpt4 book ai didi

python - 用 "#"替换字母并反转

转载 作者:行者123 更新时间:2023-12-05 09:03:40 24 4
gpt4 key购买 nike

我是 python 的新手,正在做一个测试程序,用符号替换给定文本中的所有字母。

def encrypted(request):
text = request.GET['text']

text = text.replace("a", "#.")
text = text.replace("b", "##.")
text = text.replace("c", "###.")
text = text.replace("d", "####.")
text = text.replace("e", "#####.")
text = text.replace("f", "######.")
etc...

return render(request, 'encrypted.html', {'text': text})

我已经做到了,但我尝试以同样的方式反转它,但它不起作用。

def decrypted(request):
ftext = request.GET['text']

ftext = ftext.replace("#.", "a")
ftext = ftext.replace("##.", "b")
ftext = ftext.replace("###.", "c")
ftext = ftext.replace("####.", "d")
ftext = ftext.replace("#####.", "e")
etc...

return render(request, 'decrypted.html')

因此文本根本不会出现在页面上。

<html lang="en">
<head>
<meta charset="UTF-8">
<title>yCrypt</title>
</head>
<body>
TEXT DECRYPTION: {{ftext}}
</body>
</html>

我想知道为什么它没有显示任何代码问题。也许有更简单的方法可以实现这一点?

最佳答案

我并没有完全理解你在这里尝试做的事情,但是你在 decrypted 函数中的第一个 replace 调用将查找并替换每一个出现的“#。”每个“加密字母”中都有字母“a”,而不仅仅是“a”。

随后对 replace 的调用不会匹配任何内容,因为它们的结尾是“#”。已被错误地替换为字母“a”。

要使其按设计工作,您必须颠倒 replace 调用的顺序,以便首先找到最长的匹配项。

要渲染它,您还必须在上下文中将其传递给模板渲染器。

def decrypted(request):
ftext = request.GET['text']

etc...
ftext = ftext.replace("#####.", "e")
ftext = ftext.replace("####.", "d")
ftext = ftext.replace("###.", "c")
ftext = ftext.replace("##.", "b")
ftext = ftext.replace("#.", "a")

return render(request, 'decrypted.html', { "ftext": ftext })

关于python - 用 "#"替换字母并反转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69694359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com