我试图理解此代码中的最后一行 - 我知道它在 encdic 中获取等效的明文字符(encption 字典并将它们连接在一起以创建加密消息。什么是l.lower 代码执行(获取大写字符并将其转换为小写字母?如果所有字符都已经是小写 - 我如何缩短最后一行
return s.join(encdic.get(c.lower(), c) for c in plaintext)
plaintext = "hhis is a fairly long piece of plainhexh fourscore and seven"
d = 'gikaclmnqrpoxzybdefijstuvw' #decryption key
encdic = dict(zip(alphabet, d)) #create decryption dictionary
decdic = dict(zip(d, alphabet)) #create decryption dictionary
def encrypt(plaintext, d):
s=""
return s.join(encdic.get(c.lower(), c) for c in plaintext)
当我将代码缩短为:
return s.join(encdic.get(c) for c in plaintext)
出现以下错误
TypeError: sequence item 4: expected str instance, NoneType found
我该如何解决这个问题?
更新:
我已将代码更改为:
return s.join(encdic.get(c,c) for c in plaintext)
似乎可以正常工作,但为什么呢?
请您参考如下方法:
您的 key 有两次 i 并且缺少 h
数据:
d = 'gikaclmnqrpoxzybdefijstuvw' # decryption key
测试代码:
print(sorted(list(set(d))))
print(sorted(list(d)))
结果:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
