Hacking Secret Ciphers with Python

(Ann) #1
Chapter 10 – Programming a Program to Test Our Program 149

And also remember you can use the join() string method to pass a list of strings and return a
single string:





eggs
['o', 'H', 'l', 'l', 'e']
eggs = ''.join(eggs)
eggs
'oHlle'





Randomly Scrambling a String


transpositionTest.py



  1. Convert the message string to a list to shuffle it.



  2. message = list(message)

  3. random.shuffle(message)

  4. message = ''.join(message) # convert list to string


In order to shuffle the characters in a string value, first we convert the string to a list with
list(), then shuffle the items in the list with shuffle(), and then convert back to string
value with the join() string method. Try typing the following into the interactive shell:





import random
spam = 'Hello world!'
spam = list(spam)
random.shuffle(spam)
spam = ''.join(spam)
spam
'wl delHo!orl'





We use this technique to scramble the letters in the message variable. This way we can test
many different messages just in case our transposition cipher can encrypt and decrypt some
messages but not others.


Back to the Code


transpositionTest.py


  1. print('Test #%s: "%s..."' % (i+1, message[:50]))


Line 20 has a print() call that displays which test number we are on (we add one to i because
i starts at 0 and we want the test numbers to start at 1 ). Since the string in message can be very
long, we use string slicing to show only the first 50 characters of message.

Free download pdf