【問題描述】翻譯密碼。為了保密,常不采用明文,而用密文,即按一定規則將字符轉換為另一字符,收報人則按相反的規律轉換得到原來的字符。本程式規則為:字母ascii碼加5,其他字符不變,對原文進行加密,并顯示密文。字母的最后5個加5不是字母了,處理規則為回圈成前5個。比如“X”的密文為“C”。
【樣例輸入】
please input text:I love haha.
【樣例輸出】
N qtaj mfmf.
【樣例說明】ord()函式主要用來回傳對應字符的ascii碼,chr()主要用來表示ascii碼對應的字符
uj5u.com熱心網友回復:
def text_encrypt(plaintext):
ciphertext = []
for char in plaintext:
if char.isalpha(): # 如果是字母的話
if ('v' <= char <= 'z') or ('V' <= char <= 'Z'):
ciphertext.append(chr(ord(char) - 21))
else:
ciphertext.append(chr(ord(char) + 5))
else: # 如果不是字母的情況保持不變
ciphertext.append(char)
return "".join(ciphertext)
if __name__ == '__main__':
# txt1 = 'I love haha'
# txt2 = 'vwxyz,VWXYZ'
txt = input('Please input text:')
cipher = text_encrypt(txt)
print(f"Encrypted text is: {cipher}")
uj5u.com熱心網友回復:
或者這么來:
def text_encrypt(plaintext):
ciphertext = []
for char in plaintext:
if char.isalpha(): # 如果是字母的話
char_ascii = ord(char) + 5 # 字符ascii碼先統一加5
if ('v' <= char <= 'z') or ('V' <= char <= 'Z'):
char_ascii -= 26 # 根據條件重置字母位移量
ciphertext.append(chr(char_ascii))
else: # 如果不是字母的情況保持不變
ciphertext.append(char)
return ''.join(ciphertext)
if __name__ == '__main__':
txt = input('Please input text:')
cipher = text_encrypt(txt)
print(f'Encrypted text is:{cipher}')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/75153.html
上一篇:SAMF代碼中 szid = floor((tmp-1)/(size(cos_window,2)))+1; 什么意思啊?
