issue80:python_-_partie_50
Différences
Ci-dessous, les différences entre deux révisions de la page.
Prochaine révision | Révision précédente | ||
issue80:python_-_partie_50 [2014/01/22 16:12] – créée andre_domenech | issue80:python_-_partie_50 [2014/05/07 10:55] (Version actuelle) – auntiee | ||
---|---|---|---|
Ligne 3: | Ligne 3: | ||
s = str.translate(table[, | s = str.translate(table[, | ||
+ | |||
+ | **Ce mois-ci , je vais parler de deux fonctions un peu moins connues : maketrans et translate. Nous allons commencer par la méthode translate. La méthode translate retourne une copie d'une chaîne, avec tous les caractères de la table translate remplacés (traduits) ou bien avec des caractères supprimés de la chaîne, s'ils sont contenus dans ' | ||
+ | |||
+ | s = str.translate(table[, | ||
+ | ** | ||
Before we get to the table portion of the method, let’s look at the delete portion. Let’s say that you have the string “The time has come”. And you want to delete all the vowels (for some weird reason) from that string. You can code it like this: | Before we get to the table portion of the method, let’s look at the delete portion. Let’s say that you have the string “The time has come”. And you want to delete all the vowels (for some weird reason) from that string. You can code it like this: | ||
Ligne 13: | Ligne 18: | ||
“Th tm hs cm” | “Th tm hs cm” | ||
+ | |||
+ | **Avant de passer à la partie ' | ||
+ | |||
+ | astr = "The time has come" | ||
+ | |||
+ | astr.translate (None,' | ||
+ | |||
+ | cela retourne : | ||
+ | |||
+ | "Th tm hs cm"** | ||
Notice that we included None as the translate table. While this part is cool, it gets better. There is a function called maketrans. It takes an input string and an output string as parameters and returns a table that is used as the first parameter into the translate method. Here (top right) is a very simple example. | Notice that we included None as the translate table. While this part is cool, it gets better. There is a function called maketrans. It takes an input string and an output string as parameters and returns a table that is used as the first parameter into the translate method. Here (top right) is a very simple example. | ||
Ligne 19: | Ligne 34: | ||
“Th2 t3m2 h1s c4m2” | “Th2 t3m2 h1s c4m2” | ||
+ | |||
+ | **Notez que nous avons inclus « None » comme table de traduction. Bien que cette méthode soit déjà assez sympa, il y a mieux avec une autre méthode appelée « maketrans ». Cette méthode utilise une chaîne d' | ||
+ | |||
+ | Cela retourne : | ||
+ | |||
+ | "Th2 t3m2 c4m2 H1S" | ||
+ | ** | ||
Let’s look at what this does. We assign intable to a string of vowels as before. outtable is assigned the numbers 1,2,3,4,5 as a string. When we make the call to maketrans, our actual trantable is as follows (shown below. The “\x” means that it is hexadecimal char): | Let’s look at what this does. We assign intable to a string of vowels as before. outtable is assigned the numbers 1,2,3,4,5 as a string. When we make the call to maketrans, our actual trantable is as follows (shown below. The “\x” means that it is hexadecimal char): | ||
Ligne 25: | Ligne 47: | ||
1bcd2fgh3jklmn4pqrst5vwxyz | 1bcd2fgh3jklmn4pqrst5vwxyz | ||
+ | |||
+ | **Regardons comment ça marche... Nous attribuons « intable » à une chaîne de voyelles comme auparavant, « outtable » utilise les numéros 1,2,3,4,5 comme une chaîne. Lorsque nous faisons appel à « maketrans », notre « trantable » réelle est la suivante (illustrée ci-dessous " | ||
+ | |||
+ | Si vous regardez attentivement, | ||
+ | |||
+ | 1bcd2fgh3jklmn4pqrst5vwxyz | ||
+ | ** | ||
If you look even closer, you’ll see that there actually 256 entries starting with “\x00” and ending with “\xff”. So the table contains the entire 256 possible ascii character set. So, when the translate method gets the table, it iterates (or walks through) each character, getting that characters value in Hex, and then finds that value in the translate table and substitutes it in the output string. The Hex representation of our original astr string (‘The time has come’) is shown below. | If you look even closer, you’ll see that there actually 256 entries starting with “\x00” and ending with “\xff”. So the table contains the entire 256 possible ascii character set. So, when the translate method gets the table, it iterates (or walks through) each character, getting that characters value in Hex, and then finds that value in the translate table and substitutes it in the output string. The Hex representation of our original astr string (‘The time has come’) is shown below. | ||
So now it should be making sense. | So now it should be making sense. | ||
+ | |||
+ | **Si vous regardez encore de plus près, vous verrez qu'il y a effectivement 256 entrées, en commençant par « \x00 » et en se terminant par « \xff ». Ainsi, le tableau contient l' | ||
+ | |||
+ | Maintenant, vous devez commencer à comprendre.** | ||
Now the purpose of this whole thing. Think back to your schooling where you learned about Julius Ceasar. Whenever he wanted to send a message of a confidential matter, he would use a cipher that would shift all the letters of the alphabet three characters to the right. So, using todays english alphabet: | Now the purpose of this whole thing. Think back to your schooling where you learned about Julius Ceasar. Whenever he wanted to send a message of a confidential matter, he would use a cipher that would shift all the letters of the alphabet three characters to the right. So, using todays english alphabet: | ||
Ligne 37: | Ligne 70: | ||
While this seems very simple by today’s standards, when I was a school kid, we used this all the time to send messages to each other. We used a different index into the string to start the encryption string, the logic behind it was the same. | While this seems very simple by today’s standards, when I was a school kid, we used this all the time to send messages to each other. We used a different index into the string to start the encryption string, the logic behind it was the same. | ||
+ | |||
+ | **Alors, à quoi tout cela peut-il servir ? Faites un retour en arrière et pensez à la période où vous avez étudié le personnage de Jules César à l' | ||
+ | |||
+ | cela se transformait en : DEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABC | ||
+ | |||
+ | Bien que cela semble très simple par rapport aux normes de chiffrement d' | ||
+ | ** | ||
No one knows how effective this actually was for good old Julius. One would think that if someone intercepted the message, they would have thought that it was in some foreign language. We can only speculate. | No one knows how effective this actually was for good old Julius. One would think that if someone intercepted the message, they would have thought that it was in some foreign language. We can only speculate. | ||
We can easily use the translate method and the maketrans helper function to allow us to have fun with this. Let’s say we want to make a simple program that allows us to enter a string of “plain text” and get back an encrypted string using the same side right method that Caesar used. For simplicity sake, let’s only use uppercase characters (shown top right). | We can easily use the translate method and the maketrans helper function to allow us to have fun with this. Let’s say we want to make a simple program that allows us to enter a string of “plain text” and get back an encrypted string using the same side right method that Caesar used. For simplicity sake, let’s only use uppercase characters (shown top right). | ||
+ | |||
+ | **Personne ne sait si cette méthode fut un succès pour ce bon vieux Jules César mais on peut penser que si quelqu' | ||
+ | |||
+ | Nous pouvons facilement utiliser la méthode « translate » et la fonction « maketrans » pour nous amuser un peu avec ça. Partons du principe que nous voulons faire un programme simple qui nous permet d' | ||
Everything in the above code is pretty much what we’ve covered above or in earlier Python articles, but I’ll go over it quickly. | Everything in the above code is pretty much what we’ve covered above or in earlier Python articles, but I’ll go over it quickly. | ||
The first two lines are the in and out strings. We’ve just shifted the characters and wrapped around to create the out string. The next two lines create a table for encoding and one for decoding. Line 5 prompts the user to enter a string to encode. We then encode that string (EncString) in the next line. To decode it, we simply use the translate method on the encoded string to get the plain text back. Finally we print both strings out. Here’s the output of the program. | The first two lines are the in and out strings. We’ve just shifted the characters and wrapped around to create the out string. The next two lines create a table for encoding and one for decoding. Line 5 prompts the user to enter a string to encode. We then encode that string (EncString) in the next line. To decode it, we simply use the translate method on the encoded string to get the plain text back. Finally we print both strings out. Here’s the output of the program. | ||
+ | |||
+ | **Tout ce que vous trouverez dans le code ci-dessus est à peu près ce que nous avons vu au début de cet article ou dans les précédents articles sur Python, mais je vais expliquer rapidement... | ||
+ | |||
+ | Les deux premières lignes représentent les chaînes d' | ||
+ | ** | ||
Enter the plaintext string -> THE TIME HAS COME | Enter the plaintext string -> THE TIME HAS COME | ||
Ligne 53: | Ligne 102: | ||
Just like back in school. But let’s flesh it out just a bit to make it a bit more usable. The code is almost the same with a few exceptions. First, we have added a space to the end of the intab string and in between the “Z” and the “A” in the outtab string. This helps keep the actual words from being too obvious in the encrypted string. The next change is where we ask if the user wants to encode or decode the string. Finally we added an if statement to control what we print (shown bottom right). | Just like back in school. But let’s flesh it out just a bit to make it a bit more usable. The code is almost the same with a few exceptions. First, we have added a space to the end of the intab string and in between the “Z” and the “A” in the outtab string. This helps keep the actual words from being too obvious in the encrypted string. The next change is where we ask if the user wants to encode or decode the string. Finally we added an if statement to control what we print (shown bottom right). | ||
+ | |||
+ | **Voilà, c'est comme à l' | ||
+ | ** | ||
The output from the program is: | The output from the program is: | ||
+ | |||
+ | **La sortie du programme est :** | ||
+ | |||
Encode or Decode (E or D) -> E | Encode or Decode (E or D) -> E | ||
Enter the string -> THE TIME HAS COME | Enter the string -> THE TIME HAS COME | ||
Ligne 60: | Ligne 115: | ||
And to test the decode side of things: | And to test the decode side of things: | ||
+ | |||
+ | **Et pour tester le côté " | ||
+ | ** | ||
Encode or Decode (E or D) -> D | Encode or Decode (E or D) -> D | ||
Enter the string -> WKHCWLPHCKDVCFRPH | Enter the string -> WKHCWLPHCKDVCFRPH | ||
Ligne 65: | Ligne 123: | ||
Well, hopefully you are starting to get ideas about how to use this new information in your own code. See you next time! | Well, hopefully you are starting to get ideas about how to use this new information in your own code. See you next time! | ||
+ | |||
+ | **Eh bien, j' | ||
+ | ** | ||
issue80/python_-_partie_50.1390403546.txt.gz · Dernière modification : 2014/01/22 16:12 de andre_domenech