開始使用免費開始

字串索引與串接

這題介紹最早期的加密技術之一——凱撒密碼。它的原理是:把訊息中的每個字母,在指定字母表中往後平移固定的位數。例如,在英文字母表中,對 'xyz' 進行位移 1,會得到 'yza';解密時則反向平移。請注意,在這個例子中,'z' 會變成 'a'

因此,加密/解密需要兩個引數:文字與代表位移的整數金鑰(以上例來說,key = 1)。

你的任務是,根據字串 alphabet 中儲存的英文字母表,撰寫一個加密函式。

本練習屬於課程

Python 程式面試題實作練習

檢視課程

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

def encrypt(text, key):
  
    encrypted_text = ''

    # Fill in the blanks to create an encrypted text
    for char in text.lower():
        idx = (alphabet.____(____) + ____) % len(____)
        encrypted_text = encrypted_text + alphabet[idx]

    return encrypted_text

# Check the encryption function with the shift equals to 10
print(____("datacamp", ____))
編輯並執行程式碼