Hacking Secret Ciphers with Python

(Ann) #1
Chapter 4 – Strings and Writing Programs 41

Python that the character after the slash has a special meaning. Type the following into the
interactive shell:





print('Al\'s cat is named Zophie.')
Al's cat is named Zophie.





An escape character helps us print out letters that are hard to type into the source code. Table 4- 1
shows some escape characters in Python:


Table 4- 1. Escape Characters
Escape Character What Is Actually Printed

\ (^) Backslash ()
\' Single quote (')
\" (^) Double quote (")
\n (^) Newline
\t Tab
The backslash always precedes an escape character, even if you just want a backslash in your
string. This line of code would not work:





print('He flew away in a green\teal helicopter.')
He flew away in a green eal helicopter.
This is because the “t” in “teal” was seen as an escape character since it came after a backslash.
The escape character \t simulates pushing the Tab key on your keyboard. Escape characters are
there so that strings can have characters that cannot be typed in.
Instead, try this code:
print('He flew away in a green\teal helicopter.')
He flew away in a green\teal helicopter.





Quotes and Double Quotes


Strings don’t always have to be in between two single quotes in Python. You can use double
quotes instead. These two lines print the same thing:





print('Hello world')
Hello world
print("Hello world")




Free download pdf