Wednesday, 16 January 2013

Formatting Output


Formatting Output

The real workhorse of Python’s string handling is the string-templating
mechanism. It is used to assemble a string based on other variables, which
can be integers, floating-point numbers or other strings. To insert given
values in the middle of a string, you need to use special placeholders that
start with the character ‘%’.
The placeholders are replaced with variable values which are given
in a tuple. The template string and the corresponding input tuple are
combined with a percent sign operator, as shown below.
The placeholders must agree with the variable types, so if your variable
contains an integer, you must use placeholder ‘%d’. If your variable is
another string, the corresponding placeholder should be ‘%s’. A comprehensive
list of possible placeholders and their modifiers can be found in
the Python documentation.
Here is an example:
print "There are only %d lines in my code" % (5)
print "Hello %s of %d" % ("world", 2007)
ans = [45, 32, 12]
print "the correct answers are %d, %d, and %d" % tuple(ans)
You should guess the output. Note that on the last line the input is
given as a list which is converted to a tuple by the function tuple()
before it is used to fill in the placeholders.
You can use the ‘%d’ placeholder to convert an integer to a string. To
convert a string to the corresponding integer, use function int(). For
example, int("12") produces integer 12, but int("a12") fails since
the input contains an invalid value.

Exercise

To get some practice with the string operations, let’s consider the following
scenario. There is a song contest running on television and the audience
can vote for their favorite song and singer by SMS.
There are four songs which you are interested in: 1, 3, 9 and 11.
The competition is such that each song can be sung by any singer. Your
favorite singers are Tori, Kate and Alanis. To maximize the probability
that any of your favorite singers will get to perform at least one of the
songs, you decide to vote for all the singer–song combinations. Since
you realize that writing 12 text messages of format ‘VOTE [song] [singer]’
manually is too much work, you quickly code the script in Example 13
to do the job.

No comments:

Post a Comment