python - Python 中的凯撒密码 : remove spaces in a list

标签 python list input caesar-cipher

我正在从事 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/

相关文章:

python - 在 Python 中一次更改列表中的多个项目

python - 删除 Python 中的最后一个输入行

python - 将 Python 字典与包含的浮点值进行比较

python - OSX 上的 Autopy 屏幕截图

python - 如何通过 Parse 检查推送通知发送是否已送达

list - 在方案中创建列表的排列

python - float 双重列表?

c - 在 C 中使用文件作为输入

java - 扫描仪字符串困惑

python - 使用 Jinja 循环浏览 2D 列表