Datasheet

As you can see here, Python enables you to do what you want in triple-quoted strings. However, it does
raise one more question: What’s that
\n doing there? In the text, you created a new line by pressing the
Enter key, so why didn’t it just print the rest of the sentence on another line? Well, Python will provide an
interpretation to you in the interest of accuracy. The reason why
\n may be more accurate than showing
you the next character on a new line is twofold: First, that’s one way for you to tell Python that you’re
interested in printing a new line, so it’s not a one-way street. Second, when displaying this kind of data,
it can be confusing to actually be presented with a new line. Without the
\n, you may not know whether
something is on a new line because you’ve got a newline character or because there are spaces that lead
up to the end of the line, and the display you’re using has wrapped around past the end of the current
line and is continued on the next line. By printing
\n, Python shows you exactly what is happening.
Putting Two Strings Together
Something that you are probably going to encounter more than a few times in your programming
adventures is multiple strings that you want to print at once. A simple example is when you have sepa-
rate records of a person’s first name and last name, or their address, and you want to put them together.
In Python, each one of these items can be treated separately, as shown here:
>>> “John”
‘John’
>>> “Q.”
‘Q.’
>>> “Public”
‘Public’
>>>
Try It Out Using + to Combine Strings
To put each of these distinct strings together, you have a couple of options. One, you can use Python’s
own idea of how strings act when they’re added together:
>>> “John” + “Q.” + “Public”
‘JohnQ.Public’
How It Works
This does put your strings together, but notice how this doesn’t insert spaces the way you would expect
to read a person’s name; it’s not readable, because using the plus sign doesn’t take into account any con-
cepts of how you want your string to be presented.
You can easily insert spaces between them, however. Like newlines, spaces are characters that are treated
just like any other character, such as A, s, d, or 5. Spaces are not removed from strings, even though they
can’t be seen:
>>> “John” + “ “ + “Q.” + “ “ + “Public”
‘John Q. Public’
After you determine how flexible you need to be, you have a lot of control and can make decisions about
the format of your strings.
8
Chapter 1
04_596543 ch01.qxd 6/29/05 10:59 PM Page 8