我有一个程序,它取一个字母的位置,并通过移位的值增加位置,然后给我新的字母位置,这是一个凯撒列表功能。但是我需要能够通过shift的值以及字母的位置来增加字母的位置,所以如果我有“你好”并且shift为15,则h = 7所以7 + 15 + 0 = 22并且e将是4 + 15 + 1(e的位置)= 20但是,我不确定如何编辑我的代码,以便我可以通过其位置的值增加每个字母的位置。代码工作正常,我只需要帮助搞清楚这一步。
alphabet =['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
def caesar(plaintext,shift):
# initialize ciphertext as blank string
ciphertext = ""
# loop through the length of the plaintext
for i in range(len(plaintext)):
# get the ith letter from the plaintext
letter = plaintext[i]
# find the number position of the ith letter
num_in_alphabet = alphabet.index(letter)
print (num_in_alphabet)
# find the number position of the cipher by adding the shift
cipher_num = (num_in_alphabet + shift + 3) % len(alphabet)
# find the cipher letter for the cipher number you computed
cipher_letter = alphabet[cipher_num]
# add the cipher letter to the ciphertext
ciphertext = ciphertext + cipher_letter
# return the computed ciphertext
return ciphertext
def main():
plaintext = ("hello")
shift = 16
text = caesar(plaintext,shift)
print (text)
main()
cipher_num = (num_in_alphabet + shift + i) % len(alphabet)
或者更简单
shift = 16
chiper = ''.join([chr(((ord(c)-ord('a')+shift+i)%26)+ord('a')) for i, c in enumerate("hellow")])
assert chiper == 'xvdeir'