Hacking Secret Ciphers with Python

(Ann) #1
Chapter 18 – Hacking the Simple Substitution Cipher 257

However, if you want to have this “prettified” text as a string value instead of displaying it on the
screen, you can use the pprint.pformat() function, which returns the prettified string:





import pprint
prettifiedString = pprint.pformat(someListOfListsVar)
print(prettifiedString)
[['ant'],
['baboon', 'badger', 'bat', 'bear', 'beaver'],
['camel', 'cat', 'clam', 'cobra', 'cougar', 'coyote', 'crow'],
['deer', 'dog', 'donkey', 'duck'],
['eagle'],
['ferret', 'fox', 'frog'],
['goat']]





When we write the value of allPatterns to the wordPatterns.py file, we will use the
pprint module to prevent it from being printed crammed together all on one line.


Building Strings in Python with Lists


Almost all of our programs have done some form of “building a string” code. That is, a variable
will start as a blank string and then new characters are added with string concatenation. (We’ve
done this in many previous cipher programs with the translated variable.) This is usually
done with the + operator to do string concatenation, as in the following short program:


The slow way to build a string using string concatenation.


building = ''
for c in 'Hello world!':
building += c
print(building)


The above program loops through each character in the string 'Hello world!' and
concatenates it to the end of the string stored in building. At the end of the loop, building
holds the complete string.


This seems like a straightforward way to do this. However, it is very inefficient for Python to
concatenate strings. The reasons are technical and beyond the scope of this book, but it is much
faster to start with a blank list instead of a blank string, and then use the append() list
method instead of string concatenation. After you are done building the list of strings, you can
convert the list of strings to a single string value with the join() method. The following short
program does exactly the same thing as the previous example, but faster:

Free download pdf