是一名python初学者,尝试构建一个简单的密码,在该密码中,我遍历一个列表,然后加3以构建一个新列表,但始终收到类型错误。 lower_list =来自abcd的列表..... z
当我执行以下命令时,出现类型错误:
for i in lower_list:
shift_lower += lower_list[i:i+3]
任何人都提供有关如何在语法上正确地完成此操作的提示吗?谢谢。
答案 0 :(得分:1)
您尝试一下。
lower_list=['a','b',...,'z']
cipher_text=[chr(ord(i)+3) for i in lower_list]
['d',
'e',
'f',
...
'z',
'{',
'|',
'}']
编辑:
当字符的域和范围为a-z
时(为简洁起见,我考虑使用小写字母a-z)。这是 Caeser密码的示例。
C.T=(P.T+K)Mod26
实施:
lower_list=['a', 'b' ,'c', ..., 'z']
cipher_text=[chr((ord(s) + incr - 97) % 26 + 97) for s in lst]
您可以构建一个函数来处理加密和解密。我会这样。
def caeser_cipher(lst,incr,encrypt=True):
if encrypt:
return [chr((ord(s) + incr - 97) % 26 + 97) for s in lst]
else:
return [chr((ord(s) - incr - 97) % 26 + 97) for s in lst]
lower_letters=['a','b', ...'z']
cipher_text=caeser_cipher(lower_letters,4)
#['e', 'f', 'g', 'h', ... ,'c', 'd']
plain_text=caeser_cipher(cipher_text,4,encrypt=False)
# ['a', 'b', 'c', ...,'z']
答案 1 :(得分:0)
from string import ascii_lowercase
def encode(original_text: str) -> str:
return ''.join(
ascii_lowercase[(ascii_lowercase.index(c) + 3) % len(ascii_lowercase)]
if c in ascii_lowercase else c
for c in original_text
)
print(encode('test xyz'))
输出:
whvw abc
或者您可以为其构建转换地图:
from string import ascii_lowercase
convert_dict = {
c: ascii_lowercase[(ascii_lowercase.index(c) + 3) % len(ascii_lowercase)]
for c in ascii_lowercase
}
def encode(original_text: str) -> str:
return ''.join(
convert_dict[c]
if c in convert_dict else c
for c in original_text
)
print(encode('test xyz'))
答案 2 :(得分:0)
不需要list
来遍历字符串的字符。
所以我认为您需要这样的东西:
cipher = 3 # You could use a different cipher value
message = 'This is an example of Caesars Cipher!'
encrypted = ''.join(chr(ord(char) + cipher) for char in message)
decrypted = ''.join(chr(ord(char) - cipher) for char in encrypted)
print(encrypted)
print(decrypted)
此代码输出:
Wklv#lv#dq#h{dpsoh#ri#Fdhvduv#Flskhu$
This is an example of Caesars Cipher!