我正在嘗試制作一個簡單的Stoper密碼,并讓它主要按照我想要的方式工作。除了,我只想移動郵件中大寫的字母,并保持小寫字母不變。例如,如果消息是“HeLLo”,程序應該只移動“H LL”并保持“e o”相同。如下所示。電流輸出:Message: HeLLoShift: 1IFMMP所需輸出:Message: HeLLoShift: 1IeMMo代碼:plain_text = input("Message: ")shift = int(input("Shift: "))def caesar(plain_text, shift): cipher_text = "" for ch in plain_text: if plain_text.lower(): plain_text = plain_text if ch.isalpha(): final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A')) cipher_text += final_letter else: cipher_text += ch print(cipher_text) return cipher_textcaesar(plain_text, shift)
2 回答

慕哥9229398
TA貢獻1877條經驗 獲得超6個贊
您可以添加條件來檢查該字符是否為小寫字符,并僅在它不是小寫字符時才對其進行加密。ch != ch.lower()
plain_text = input("Message: ")
shift = int(input("Shift: "))
def caesar(plain_text, shift):
cipher_text = ""
for ch in plain_text:
if ch.isalpha() and ch != ch.lower():
final_letter = chr((ord(ch) + shift - ord('A')) % 26 + ord('A'))
cipher_text += final_letter
else:
cipher_text += ch
print(cipher_text)
return cipher_text
caesar(plain_text, shift)

墨色風雨
TA貢獻1853條經驗 獲得超6個贊
我認為你需要:
def caesar(plain_text, shift):
return "".join([chr(ord(i)+shift) if i.isupper() else i for i in plain_text])
caesar(plain_text, shift)
添加回答
舉報
0/150
提交
取消