2017-08-17 3 views
-1

私は両方のアルファベットの辞書を使って簡単な暗号を書こうとしていますが、 "TypeError:文字列インデックスは整数でなければなりません"というエラーが出ています。どのように私はcの値をインデックス化するのですか?すぐに私は、「結果」と「暗号文」を置き換えると私のためのシンプルな暗号が索引付けの動作していませんか?

cipher_alphabet = dict(zip('abcdefghijklmnopqrstuvwxyz', 
'phqgiumeaylnofdxjkrcvstzwb')) 

def cipher(text, cipher_alphabet, option='encipher'): 
    result = "" 
    for c in text: 
     if c in cipher_alphabet: 
      result = result + cipher_alphabet[c] 
     else: 
      result = result + c 
    print(ciphertext) 
+0

は何であるかの問題がわからない定義されていないされているciphertext'。例えば'print(result)'は暗号化されたテキストを出力します。 – AChampion

+0

関数の呼び出し方法を表示できますか?エラーがある可能性があります – user3080953

+0

ありがとう、私は印刷コマンドを修正しましたが、それはまだ同じエラーです。私はこれを次のように呼んでいる: 暗号( '城の東壁を守る'、 'd') – PikNikki

答えて

0

ワークス:だからresultciphertextを固定

>>> cipher_alphabet = dict(zip('abcdefghijklmnopqrstuvwxyz', 
'phqgiumeaylnofdxjkrcvstzwb')) 

>>> def cipher(text, cipher_alphabet, option='encipher'): 
    result = "" 
    for c in text: 
     if c in cipher_alphabet: 
      result = result + cipher_alphabet[c] 
     else: 
      result = result + c 
    print result 


>>> cipher("bloo",cipher_alphabet) 
hndd 
+0

aha!私はそれを間違って呼んでいる。私はdictを呼んでいませんでした!そんなにありがとう。 – PikNikki

0

が、それは動作しますが、これを行うための他の方法は、例えば、ありますデフォルト値でdict.get()を使用して:

def cipher(text, cipher_alphabet, option='encipher'): 
    return ''.join(cipher_alphabet.get(c, c) for c in text) 

>>> cipher('hello world', cipher_alphabet) 
einnd tdkng 

str.maketrans使用: `以外

cipher_alphabet = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'phqgiumeaylnofdxjkrcvstzwb') 

def cipher(text, cipher_alphabet, option='encipher'): 
    return text.translate(cipher_alphabet) 

>>> cipher('hello world', cipher_alphabet) 
einnd tdkng 
関連する問題