Reputation: 271
I'm going through exercises in a python book and I'm a bit puzzled by what is going on in this code.
formatter = "%r %r %r %r"
print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
"I had this thing.",
"That you could type up right.",
"But it didn't sing.",
"So I said goodnight."
)
The author offer no explanation as to what "formatter" is doing after each "print". If I remove them, everything prints out exactly the same. Am I missing something here?
Upvotes: 3
Views: 1404
Reputation: 3031
That's the classic format for string formatting, print "%r" % var
will print the raw value of var, four %r expects 4 variables to be passed after the %.
A better example would be:
formatter = "first var is %r, second is %r, third is %r and last is %r"
print formatter % (var1, var2, var3, var4)
The use of a formatter variable is just to avoid using a long line in the print but usually there's no need of that.
print "my name is %s" % name
print "the item %i is $%.2f" % (itemid, price)
%.2f
is float with 2 values after comma.
There's a newer variant of string formatting you may wish to try: (if you're using at least 2.6)
print "my name is {name} I'm a {profession}".format(name="sherlock holmes", profession="detective")
More at:
http://www.python.org/dev/peps/pep-3101/
http://pythonadventures.wordpress.com/2011/04/04/new-string-formatting-syntax/
Upvotes: 2
Reputation: 310049
formatter
is a string. so, the first line is the same as:
"%r %r %r %r" % (1, 2, 3, 4)
which calls repr
on each of the items in the tuple on the right and replaces the corresponding %r
by the result. Of course, it does the exact same thing for
formatter % ("one", "two", "three", "four")
and so on as well.
Note that you'll often also see:
"%s %s %s %s" % (1, 2, 3, 4)
which calls str
instead of repr
. (In your example, I think that str
and repr
return the same things for all of those objects, so the output will be exactly the same if you change formatter
to use %s
instead of %r
)
Upvotes: 2
Reputation: 1123420
No, it does not print out the exact same thing. There are no commas, and no parenthesis if you use the formatter %
part.
It'll be clearer if you expand the formatter. I suggest you use:
formatter = "One: %r, Two: %r, Three: %r, Four: %r"
instead.
The formatter acts as a template, each %r
acting as a place holder for the values in the tuple on the right-hand side.
Upvotes: 2