2017-08-17 2 views
-1

J'essaye d'écrire un chiffre simple, en utilisant un dictionnaire pour les deux alphabets, et je reçois toujours une erreur "TypeError: les index de chaîne doivent être des entiers". Comment puis-je indexer la valeur de c ??chiffrement simple ne fonctionne pas bc d'indexation?

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

Autre que 'ciphertext' étant non défini pas sûr de ce problème est. par exemple. 'print (result)' imprime le texte crypté. – AChampion

+0

Pouvez-vous montrer comment vous appelez la fonction? L'erreur pourrait être là – user3080953

+0

Merci, j'ai corrigé la commande d'impression, mais c'est toujours la même erreur. Je l'appelle comme ceci: chiffre ('défendre le mur est du château', 'd') – PikNikki

Répondre

0

Works pour moi, dès que je remplace « cryptogramme » par « résultat »:

>>> 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! Je l'ai appelé mal. Je n'appelais pas le dict! Merci beaucoup pour ça. – PikNikki

0

fixation Alors ciphertext-result fait fonctionner, mais il y a d'autres façons de le faire, par exemple en utilisant dict.get() avec une valeur par défaut:

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 

En utilisant 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