我創建了一個簡單的程序,用於在用戶輸入的字符串上執行Caeser密碼。當過去的結束範圍內在列表內移動?
爲了讓轉移越過列表的末尾並返回到開頭,我只是簡單地複製了該列表的所有列表值。
是否有一個更pythonic的方式來實現這個結果,以便它將轉移回到開始,並繼續轉移,如果移動超過列表範圍的結束?
while True:
x = input("Enter the message you would like to encrypt via a Caeser shift; or type 'exit': ")
if x == 'exit': break
y = int(input("Enter the number by which you would like to have the message Caeser shifted: "))
alphabet = list('abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz')
encoded = ''
for c in x:
if c.lower() in alphabet:
encoded += alphabet[alphabet.index(c)+y] if c.islower() else alphabet[alphabet.index(c.lower())+y].upper()
else:
encoded += c
print(encoded)
這正是我所期待的。我還沒有熟悉模塊化算術,但它看起來像是一個偉大的技巧,在我的武庫。名單上的好點也是如此。 – roflmyeggo