04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

24 CHAPTER 1 ■ INSTANT HACKING: THE BASICS<br />

we don’t have to. It’s just convenient. An alternative is to use the backslash character (\) to<br />

escape the quotes in the string, like this:<br />

>>> 'Let\'s go!'<br />

"Let's go!"<br />

Python understands that the middle single quote is a character in the string and not the<br />

end of the string. (Even so, Python chooses to use double quotes when printing out the string.)<br />

The same works with double quotes, as you might expect:<br />

>>> "\"Hello, world!\" she said"<br />

'"Hello, world!" she said'<br />

Escaping quotes like this can be useful, and sometimes necessary. For example, what would<br />

you do without the backslash if your string contained both a single quote and a double quote,<br />

as in the string 'Let\'s say "Hello, world!"'?<br />

■Note Tired of backslashes? As you will see later in this chapter, you can avoid most of them by using long<br />

strings and raw strings (which can be combined).<br />

Concatenating Strings<br />

Just to keep whipping this slightly tortured example, let me show you another way of writing<br />

the same string:<br />

>>> "Let's say " '"Hello, world!"'<br />

'Let\'s say "Hello, world!"'<br />

I’ve simply written two strings, one after the other, and Python automatically concatenates<br />

them (makes them into one string). This mechanism isn’t used very often, but it can be useful<br />

at times. However, it only works when you actually write both strings at the same time, directly<br />

following one another:<br />

>>> x = "Hello, "<br />

>>> y = "world!"<br />

>>> x y<br />

SyntaxError: invalid syntax<br />

In other words, this is just a special way of writing strings, not a general method of concatenating<br />

them. How, then, do you concatenate strings? Just like you add numbers:<br />

>>> "Hello, " + "world!"<br />

'Hello, world!'<br />

>>> x = "Hello, "<br />

>>> y = "world!"<br />

>>> x + y<br />

'Hello, world!'

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!