【问题标题】:trying to Write a Python program to create a Caesar encryption试图编写一个 Python 程序来创建一个凯撒加密
【发布时间】:2020-09-13 13:01:53
【问题描述】:
string = input("Enter your string ")
for i in string:
     alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
     cipher = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
     char = alphabet.find(i)
     ciphered = string.replace(i,cipher[char])
print(ciphered)

知道为什么这个只返回更改后的字符串的最后一个字母吗?

【问题讨论】:

    标签: python string encryption


    【解决方案1】:

    每次执行循环时,您都在string 中替换一个字母,然后将该单个字母替换的结果分配给ciphered,覆盖它之前的任何值。最后得到的值是上次循环迭代期间分配的值。

    实际上通过replace 修改字符串是个坏主意,因为你最终会来回翻转相同的字母。相反,您可以迭代地构建加密字符串:

    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
    cipher = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
    ciphered = ""
    for char in string:
        i = alphabet.find(char)
        ciphered += cipher[i]
    

    【讨论】:

      【解决方案2】:

      只有最后一个字母被更改,因为您在每个循环上从原始输入字符串创建一个ciphered 字符串,因此在最后一个循环中,只有最后一个元素被更改。

      string = input("Enter your string ")
      ciphered = ""
      alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
      cipher = "ZYXWVUTSRQPONMLKJIHGFEDCBA"
      for i in string:
           char = alphabet.find(i)
           ciphered += cipher[char]
      print(ciphered)
      

      这应该可行。

      【讨论】:

        【解决方案3】:

        也许您还应该将字符串转换为大写字母,否则 find() 函数会返回值 -1。

        string = string.capitalize()
        
        

        【讨论】:

          猜你喜欢
          • 2022-09-30
          • 2013-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-29
          • 2014-03-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多