【问题标题】:Decryption not working in Caesar cipher in Python解密在 Python 中的凯撒密码中不起作用
【发布时间】:2015-11-23 11:43:16
【问题描述】:

我的加密工作正常,但是当我运行解密代码时,它不起作用。当我到达那部分代码时,会出现错误 -

cipher2 += cipher[(cipher(A)-key1)%(len(cipher2))] TypeError:“str”对象不可调用

如果您能花时间帮助我,我将不胜感激。

alphabetL = 'abcdefghijklmnopqrstuvwxyz'
alphabetC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = '0123456789'
space = ' '
Ll = len(alphabetL)
Lc = len(alphabetC)
Ln = len(number)
Lall = Ll + Lc + Ln
msgall = alphabetL + alphabetC + number + space
Question1 = input("Hello, please insert the message you want encrypted: ")
key1 = int(input("Please insert the key you want used [Keep between 1 and 26]: "))
cipher = ''
cipher2 = ''


for A in Question1:
    if A in alphabetL:
        cipher += alphabetL[(alphabetL.index(A)+key1)%Ll]
    elif A in alphabetC:
        cipher += alphabetC[(alphabetC.index(A)+key1)%Lc]
    elif A in number:
        cipher += number[(number.index(A)+key1)%Ln]
    elif A in space:
        cipher += space
    else:
        print ("Error, please use abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
print (cipher)

Question2 = input("Would you like to decrypt the message? [Y/N]: ")
if Question2 == "Y":
    for A in cipher:
        cipher2 += cipher[(cipher(A)-key1)%(len(cipher2))]
    print (cipher2)

【问题讨论】:

  • 问题出在倒数第二行的cipher(A) 部分。 cipher 变量是一个字符串,不能像函数一样调用。您是否尝试改为调用 .index() 方法?
  • 我不确定。你会把它改成什么?
  • 您可能需要考虑使用enumerate() 而不是在字符串本身上调用.index() 方法。
  • 对不起,没用
  • 在倒数第二行调用cipher(A) 的目的是什么?

标签: python encryption caesar-cipher


【解决方案1】:

您可以创建一个用于加密和解密的函数。

alphabetL = 'abcdefghijklmnopqrstuvwxyz'
alphabetC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = '0123456789'
space = ' '
Ll = len(alphabetL)
Lc = len(alphabetC)
Ln = len(number)
Lall = Ll + Lc + Ln
msgall = alphabetL + alphabetC + number + space
Question1 = input("Hello, please insert the message you want encrypted: ")
key1 = int(input("Please insert the key you want used [Keep between 1 and 26]: "))

cipher2 = ''

def ceaser_cipher(Question1,key1):
    cipher = ''
    for A in Question1:
        if A in alphabetL:
            cipher += alphabetL[(alphabetL.index(A)+key1)%Ll]
        elif A in alphabetC:
            cipher += alphabetC[(alphabetC.index(A)+key1)%Lc]
        elif A in number:
            cipher += number[(number.index(A)+key1)%Ln]
        elif A in space:
            cipher += space
        else:
            print ("Error, please use abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

    return cipher


cipher=ceaser_cipher(Question1,key1)
print (cipher)
Question2 = input("Would you like to decrypt the message? [Y/N]: ")
if Question2 == "Y":
    cipher2=ceaser_cipher(cipher,-key1)
    print (cipher2)

【讨论】:

  • 当我运行代码时,出现错误消息“NameError: name 'raw_input' is not defined”。你能给我什么建议吗?
  • @BigTommyVernon 这意味着您正在使用 python-3.x 。我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-03
  • 2014-03-30
  • 1970-01-01
  • 2013-02-26
相关资源
最近更新 更多