2017-10-21 92 views
0

我在做python中的加密分配,我需要: - 分割字符串 - 替換字母 - 重新加入它,以便它是一個單詞。python如何分割字符串並重新加入

這是完整的代碼,但我卡在def encode(plain)下的for循環。

""" crypto.py 
Implements a simple substitution cypher 
""" 

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
key = "XPMGTDHLYONZBWEARKJUFSCIQV" 

def menu(): 

    print("Secret decoder menu") 
    print("0) Quit") 
    print("1) Encode") 
    print("2) Decode") 
    print("What do you want to do?") 
    response = input() 
    return response 

def encode(plain): 

for i in range(len(plain)): 

    plain = plain.upper() 
    x = plain[i:i+1] 
    y = alpha.index(x) 
    z = key[y:y+1] 
    plain[x] = z 

return plain 

def main(): 

keepGoing = True 
    while keepGoing: 

    response = menu() 

    if response == "1": 

     plain = input("text to be encoded: ") 
     print(encode(plain)) 

    elif response == "2": 
     coded = input("code to be decyphered: ") 
     print (decode(coded)) 

    elif response == "0": 
     print ("Thanks for doing secret spy stuff with me.") 
     keepGoing = False 

    else: 
     print ("I don't know what you want to do...") 

return main 

main() 
menu() 
+4

樣品的輸入和輸出預計將是很好的。 –

+2

你需要在你的函數定義下縮進代碼 – 0TTT0

+0

解密器菜單的祕密 0)退出 1)編碼 2)解碼 你想做什麼? 文本進行編碼:你好 大號 牛逼 ž ž Ë HELLO – Matteo

回答

1

實現這個替代的最簡單的方法是使用字典和列表理解:

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
key = "XPMGTDHLYONZBWEARKJUFSCIQV" 
converter = {a:b for a, b in zip(alpha, key)} 
def encode(s): 
    return ''.join(converter[i] for i in s) 

def decode(s): 
    reverse = {b:a for a, b in converter.items()} 
    return ''.join(reverse[i] for i in s) 

def main(): 
    response = input("Enter 1 to decode, 2 to encode: ") 
    if response == "1": 
     the_string = input("Enter the scrambled string: ") 
     print("The result is ", decode(the_string)) 
    elif response == "2": 
     the_string = input("Enter the plain string: ") 
     print("The result is ", encode(the_string)) 
main() 
+0

在你的代碼中,'reverse'和'converter'結束。我將使用'converter = dict(zip(alpha,key))'和'reverse = dict(zip(key,alpha))'(或'reverse = {b:a for a,b in converter.items()} ')。 –

+0

@MatthiasFripp謝謝你指出。請參閱我最近的編輯。 – Ajax1234

0

如果你想實現自己的解決方案也爲@ Ajax1234說。

但更容易string translate

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
key = "XPMGTDHLYONZBWEARKJUFSCIQV" 
crypto = maketrans(alpha, key) 

.... 
the_string = input("Enter the scrambled string: ") 
the_string = the_string.upper() 
encrypted = the_string.translate(crypto) 
+0

我的教授告訴我們只使用標準代碼,所以我們不能使用translate()方法。我們也不能改變main()函數,所以我們基本上必須使用字符串操作來轉換祕密消息。在def encode下(普通),我已經將字符串「plain」切片並將字符與字符串「alpha」和「key」進行比較,但我不知道如何再次將它們組合成一個單詞 – Matteo