我需要创建一个简单的凯撒密码编码器/解码器,我不确定最好的方法,字符串?名单?循环?
Word = input("What do you want to decode")
Shift = input("What do you want the shift to be?")
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"]
for letters in Word:
if letters == [alphabet.index(letters)]:
print [alphabet.index(letters + Shift)]
for a in alphabet:
if a == letters:
print (letters+(alphabet.index(letters)))
如您所知,我尝试过for
循环来分离列表项并进行比较,但是它没有工作,所以我不知道如何继续,不能使用translate
或order
函数。
发布于 2022-04-04 00:34:12
alphabet
列表至少缺少一个字母,因此这可能会影响您的结果。我建议用string.ascii_uppercase
代替.if letters == [alphabet.index(letters)]
中,你混淆了这个字母(letters
--实际上这只是一个字母!)对于字母的index
,alphabet
;它们不可能是相同的,因为一个是字符串,另一个是int。无论如何,您不需要循环来查找索引;index
函数会为您执行此操作。%
)操作符是一种简单的方法。alphabet
中的字符。import string
word = input("What do you want to decode? ").upper()
shift = int(input("What do you want the shift to be? "))
alphabet = string.ascii_uppercase
print(''.join(
alphabet[
(alphabet.index(c) + shift) % len(alphabet)
] if c in alphabet else c for c in word
))
What do you want to decode? ZEBRA STRIPES
What do you want the shift to be? 12
LQNDM EFDUBQE
发布于 2022-04-04 01:38:12
使用这个循环
import string
Word = input("What do you want to decode")
Shift = input("What do you want the shift to be?")
alphabet = string.ascii_uppercase
ouput = ""
for i in Word:
if i.upper() in alphabet:
if alphabet.find(i.upper())+int(Shift)>25:
ouput += alphabet[alphabet.find(i.upper())+int(Shift)-25]
else:
ouput += alphabet[alphabet.find(i.upper())+int(Shift)]
else:
ouput+=i
print(ouput)
发布于 2022-04-04 01:48:41
word = input("What do you want to decode ")
shift = input("What do you want the shift to be? ")
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_encrypt(word: str, shift: int):
return ''.join(alphabet[(alphabet.index(char) + shift) % len(alphabet)]
if char in alphabet else char for char in word)
def caesar_decript(word: str, shift: int):
return caesar_encrypt(word, 26-shift)
word = word.upper()
shift = int(shift)
encrypted_word = caesar_encrypt(word, shift)
print(encrypted_word)
decripted_word = caesar_decript(encrypted_word, shift)
print(decripted_word)
https://stackoverflow.com/questions/71730867
复制相似问题