Datasheet

Putting Strings Together in Different Ways
Another way to specify strings is to use a format specifier. It works by putting in a special sequence of
characters that Python will interpret as a placeholder for a value that will be provided by you. This may
initially seem like it’s too complex to be useful, but format specifiers also enable you to control what the
displayed information looks like, as well as a number of other useful tricks.
Try It Out Using a Format Specifier to Populate a String
In the simplest case, you can do the same thing with your friend, John Q.:
>>> “John Q. %s” % (“Public”)
‘John Q. Public’
How It Works
That %s is the format specifier for a string. Several other specifiers will be described as their respective
types are introduced. Each specifier acts as a placeholder for that type in the string; and after the string,
the
% sign outside of the string indicates that after it, all of the values to be inserted into the format speci-
fier will be presented there to be used in the string.
You may be wondering why the parentheses are there. The parentheses indicate to the string that it
should expect to see a sequence that contains the values to be used by the string to populate its format
specifiers.
Sequences are a very important part of programming in Python, and they are covered in some detail
later. For now, we are just going to use them. What is important to know at this point is that every for-
mat specification in a string has to have an element that matches it in the sequence that’s provided to it.
The items we are putting in the sequence are strings that are separated by commas (if there is more than
one). If there is only one, as in the preceding example, the sequence isn’t needed, but it can be used.
The reason why this special escape sequence is called a format specifier is because you can do some
other special things with it — that is, rather than just insert values, you can provide some specifications
about how the values will be presented, how they’ll look.
Try It Out More String Formatting
You can do a couple of useful things when formatting a simple string:
>>> “%s %s %10s” % (“John”, “Q.”, “Public”)
‘John Q. Public’
>>> “%-10s %s %10s” % (“John”, “Q.”, “Public”)
‘John Q. Public’
How It Works
In the first string, the reason why Public is so alone along the right side is because the third format
specifier in the main string, on the left side, has been told to make room for something that has 10 char-
acters. That’s what the
%10s means. However, because the word Public only has 6 characters, Python
padded the string with space for the remaining four characters that it had reserved.
9
Programming Basics and Strings
04_596543 ch01.qxd 6/29/05 10:59 PM Page 9