我正在从事 Caesar Cypher 项目。我获取用户的输入,将其转换为列表,删除空格,然后对字母进行加密。
我的问题是:如何将这些空格重新添加到最终的加密消息中?
这是我迄今为止所取得的成就(假装单词=消息)
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']
en_de = input("Do you want to encrypt or decrypt your message? ")
word = input("Enter a word: ")
shift = input("Enter a number: ")
word = list(word)
indexes = []
def encrypt():
for letters in word:
if letters in alphabet:
index = (alphabet.index(letters))
int(index)
indexes.append(index)
print(indexes)
n = 0
n = n + int(shift)
for i in range(len(indexes)):
indexes[i] = indexes[i] + n
print(indexes)
ceaser_cipher = ''
for i in indexes:
if i > len(alphabet)-1:
i %= len(alphabet)
ceaser_cipher = ceaser_cipher + (alphabet[i])
for
print(ceaser_cipher)
def decrypt():
for letters in word:
index = (alphabet.index(letters))
int(index)
indexes.append(index)
print(indexes)
n = 0
n = n + int(shift)
for i in range(len(indexes)):
indexes[i] = indexes[i] - n
print(indexes)
ceaser_cipher = ''
for i in indexes:
if i > len(alphabet)-1:
i %= len(alphabet)
ceaser_cipher = ceaser_cipher + (alphabet[i])
print(ceaser_cipher)
if en_de == "encrypt":
encrypt()
elif en_de == "decrypt":
decrypt()
最佳答案
我想要的结构是这样的:
input_string = input("Enter message or cipher: ")
input_list = input_string.split(" ")
# input_list will be a list of each word in input_string
# encrypt each word in input_list and append each encrypted word
# to a new list, let's say that list is called output_list
output = " ".join(output_list)
# output will be a string of each item in the list separated by spaces
最终的程序可能如下所示:
alphabet = list("abcdefghijklmnopqrstuvwxyz")
message = input("message or cipher: ").lower().split(" ")
shift = int(input("shift: "))
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
cipher_list = []
for word in message:
cipher_word = ""
for letter in word:
cipher_word += shifted_alphabet[alphabet.index(letter)]
cipher_list.append(cipher_word)
print(" ".join(cipher_list))
关于python - Python 中的凯撒密码 : remove spaces in a list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71552575/