問:是時候練習我們的間諜技術并編碼一個簡單的密碼了。撰寫一個函式 encode() ,詢問用戶要編碼的訊息和一個整數鍵值。密碼將通過將密鑰添加到字符的 Unicode 值來移動訊息中的每個字符。例如,'A'(unicode 65)移位 3 產生 'D'(unicode 68)。
請確保您的輸出只是密文。
輸出應該是:
輸入資訊:時間到了,海象說
輸入密鑰:7
[ol'{ptl'ohz'jvtl3'{ol'^hsyz'zhpk
uj5u.com熱心網友回復:
您可以考慮使用chr、ord和:str.join(iterable)
def get_int_input(prompt: str) -> int:
while True:
try:
num = int(input(prompt))
break
except ValueError:
print('Error: Enter an integer, try again...')
return num
def encode(message: str, key: int) -> str:
return ''.join(chr(ord(ch) key) for ch in message)
def main() -> None:
message = input('Enter a message: ')
key = get_int_input('Enter a key: ')
encoded = encode(message, key)
print(encoded)
if __name__ == '__main__':
main()
示例用法:
Enter a message: The time has come, the Walrus said
Enter a key: 7
[ol'{ptl'ohz'jvtl3'{ol'^hsy|z'zhpk
uj5u.com熱心網友回復:
您可以使用chr()andord()移動每個字符并將join()結果重新組合在一起:
s = "The time has come, the Walrus said"
k = 7
e = "".join(chr(ord(c) k) for c in s)
print(e)
[ol'{ptl'ohz'jvtl3'{ol'^hsy|z'zhpk
uj5u.com熱心網友回復:
這是一個簡單的凱撒密碼 無論如何這是代碼
def encrypt(text, s):
result = ""
# transverse the plain text
for i in range(len(text)):
char = text[i]
# Encrypt uppercase characters in plain text
if (char.isupper()):
result = chr((ord(char) s-65) % 26 65)
# Encrypt lowercase characters in plain text
else:
result = chr((ord(char) s - 97) % 26 97)
return result
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/429468.html
