python - Python 字符串操作 - 替换函数以创建凯撒密码
问题描述
我的代码遇到了问题,我怀疑是我使用了替换方法,但我不确定。我想编写一个代码,使用移位为 1 的凯撒密码对变量明文引用的字符串进行加密,然后将结果存储在变量密文中;存储它是我的值不正确的地方。
plaintext = 'thequickbrownfoxjumpsoverthelazydog'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
ciphertext = 'thequickbrownfoxjumpsoverthelazydog'
for i in range(len(plaintext)):
j = plaintext[i]
j_index = alphabet.index(j)
if j_index + 13 >= 26:
j_index = (j_index + 13) % 26
else:
j_index+=13
ciphertext = ciphertext.replace(j,alphabet[j_index])
print(ciphertext[i])
print(ciphertext)
当我打印每个单独的字符时,它给了我想要的结果,但是当我打印整个密文时,一些字母不同并且值不正确。感谢帮助,TIA。
我希望我的输出是:'gurdhvpxoebjasbkwhzcfbiregurynmlqbt',而不是我得到'turquickbrbwnfbkwumcfbirrturlnmlqbt'
编辑修复代码并添加输出。
解决方案
问题是字符被多次替换,因为我们在整个字符串中替换而不是在确切位置
plaintext = 'thequickbrownfoxjumpsoverthelazydog'
alphabet = 'abcdefghijklmnopqrstuvwxyz'
ciphertext = 'thequickbrownfoxjumpsoverthelazydog'
ciphertextfinal = ''
for i in range(len(plaintext)):
j = plaintext[i]
j_index = alphabet.index(j)
if j_index + 13 >= 26:
j_index = (j_index + 13) % 26
else:
j_index+=13
ciphertext = ciphertext.replace(j,alphabet[j_index])
ciphertextfinal += ciphertext[i]
print(ciphertext[i])
print(ciphertextfinal)
#prints gurdhvpxoebjasbkwhzcfbiregurynmlqbt
我只是使用了替换的位置,并通过连接到一个变量中来制作一个字符串
推荐阅读
- paypal - 为什么使用 PayPal API?
- sql - 复合键:外键和主键
- python - 使用上行链接在 Anvil 中上传 csv 文件
- windows - .htaccess 文件在我的 codeigniter 应用程序中导致禁止错误,我在我的 Windows 服务器中运行 apache 24
- django - 从分配的对象获取 ForeignKey 对象时出错
- prometheus - 图计数 Prometheus PushGateway API 调用
- javascript - 第一个 NodeJS 应用程序 - 如何解决 MODULE NOT FOUND 和其他问题?
- c# - 填充项目列表时C#无法更新组合框
- gitlab - 如果用户几天不登录,是否可以禁用 Gitlab 锁定 LDAP 帐户?
- sql - 如何将 JOIN 表中的 ID 迁移到 PostgreSQL 中的外键列