首页 > 解决方案 > 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'

编辑修复代码并添加输出。

标签: python

解决方案


问题是字符被多次替换,因为我们在整个字符串中替换而不是在确切位置

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

我只是使用了替换的位置,并通过连接到一个变量中来制作一个字符串


推荐阅读