16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

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 <strong>to</strong>. It’s just convenient. An alternative is <strong>to</strong> use the backslash character (\) <strong>to</strong><br />

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

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

"Let's go!"<br />

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

end of the string. (Even so, <strong>Python</strong> chooses <strong>to</strong> 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 <strong>to</strong> keep whipping this slightly <strong>to</strong>rtured 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 <strong>Python</strong> au<strong>to</strong>matically concatenates<br />

them (makes them in<strong>to</strong> 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!