2017-06-26 35 views
1

基本上我有一個函數,將非常簡單地加密一條消息。找到簡單的方法來翻譯基於密鑰的字符串

def encrypt(message): 
    alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] 
    key = ["4","x","z","@","%","b","j","q","(","ƒ","¥","µ","˚","nå","ø","π","å","œ","¢","∞","∫","µ","≈","`","¬","…"] 
    new_message = "" 
    for x in range(0,len(message)): 
     new_message = message.replace(message[x],key.index[alphabet.index(message[x])]) 
    return new_message 

print(encrypt(input("What would you like to encrypt").lower())) 

這應該採信,並在列表鍵相同的索引字符替換它,但我得到的錯誤:

TypeError: 'builtin_function_or_method' object is not subscriptable 
+1

有這樣做的更好的方法,但你的問題是'key.index [alphabet.index(message [x])]''。改爲使用'鍵[alphabet.index(message [x])]'。 –

+1

@JaredGoguen我不認爲這會起作用,一些鑰匙包含在字母表中。這是'str.translate'的一個用例。 –

+0

@ juanpa.arrivillaga哈哈,同意......直到我發佈我的答案後纔看到此消息。 –

回答

2

最後一個用例爲str.translate!請注意,key中的一個條目由兩個字符組成。如果這是有意的,並且您想用兩個字符替換單個字符,則可以手動創建翻譯表。

table = dict(zip(map(ord, alphabet), key)) 
+1

@Sumtinlazy你讀過'str.translate '鏈接的文檔? –

+0

沒有看到,我的壞。 – Sumtinlazy

2

key.index()需要一個值,並返回其索引,並用它()[]所以你需要修復這一行:

new_message = message.replace(message[x],key.index[alphabet.index(message[x])]) 

到:

new_message = message.replace(message[x],key[alphabet.index(message[x])]) 

這將採取字母索引並使用它訪問key列表並獲取該索引處的值以將其替換爲原始字母。

編輯: 一個更好的辦法來做到這一點是使用dictionary,構建一個新的字符串isntead,以避免重複replace()string

dic = {'a': '4', 'b': 'x', 'c': 'z' ...} 
new_message = '' 
for x in message: 
    new_message += dic[x] 
return new_message 
2

我建議使用一箇中間dict創建alphabet列表項的映射與key列表項:

>>> alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] 
>>> key = ["4","x","z","@","%","b","j","q","(","ƒ","¥","µ","˚","nå","ø","π","å","œ","¢","∞","∫","µ","≈","`","¬","…"] 

# Your `dict` object with the mapping between both the list 
>>> encryption_dict = dict(zip(alphabet, key)) 

然後使用上面的字典str.join(...)來轉換你的字符串。例如:

>>> my_str = 'stackoverflow' 

# Transform the string using the `dict` and join the chars to form single string   
>>> new_str = ''.join(encryption_dict.get(s, s) for s in my_str) 
#           ^
#  to return same character if not present in alphabet list 

>>> print(new_str) 
¢∞4z¥øµ%œbµø≈ 
+0

如果不使用中間虛擬值,這將不起作用,因爲某些鍵是字母表。 –

+0

@ juanpa.arrivillaga我認爲你的意思是某些字符*不在*字母表列表中?我更新了答案來處理它通過使用'dict.get(..)' –

+0

這很好,但我想知道這是如何不同於我之前嘗試 – Sumtinlazy

相關問題