Hacking Secret Ciphers with Python

(Ann) #1

42 http://inventwithpython.com/hacking


Email questions to the author: [email protected]


Hello world


But you cannot mix single and double quotes. This line will give you an error:





print('Hello world")
SyntaxError: EOL while scanning single-quoted string





I like to use single quotes so I don’t have to hold down the shift key on the keyboard to type
them. It’s easier to type, and the computer doesn’t care either way.


But remember, just like you have to use the escape character \' to have a single quote in a string
surrounded by single quotes, you need the escape character \" to have a double quote in a string
surrounded by double quotes. For example, look at these two lines:





print('I asked to borrow Alice\'s car for a week. She said, "Sure."')
I asked to borrow Alice's car for a week. She said, "Sure."
print("She said, \"I can't believe you let him borrow your car.\"")
She said, "I can't believe you let him borrow your car."





You do not need to escape double quotes in single-quote strings, and you do not need to escape
single quotes in the double-quote strings. The Python interpreter is smart enough to know that if a
string starts with one kind of quote, the other kind of quote doesn’t mean the string is ending.


Practice Exercises, Chapter 4, Set A


Practice exercises can be found at http://invpy.com/hackingpractice 4 A.


Indexing


Your encryption programs will often need to get a single character from a string. Indexing is the
adding of square brackets [ and ] to the end of a string value (or a variable containing a string)
with a number between them. This number is called the index, and tells Python which position in
the string has the character you want. The index of the first character in a string is 0. The index 1
is for the second character, the index 2 is for the third character, and so on.


Type the following into the interactive shell:





spam = 'Hello'
spam[0]
'H'
spam[1]
'e'




Free download pdf