[Tutor] Defining a "format string"

Steven D'Aprano steve at pearwood.info
Sun Jun 26 13:24:12 CEST 2011


Lisi wrote:
> In the following excerpt from a program in the book I am following:
> 
>    print "If I add %d, %d, and %d I get %d." % ( 
>       my_age, my_height, my_weight, my_age + my_height + my_weight)
> 
> is 
> 
> % ( 
>       my_age, my_height, my_weight, my_age + my_height + my_weight)
> 
> the/a format string?


No. The format string is a string with the % codes. In this case, they 
are all %d codes:

"If I add %d, %d, and %d I get %d."

but there are other codes possible.

The % symbol on its own is an operator, like + or * or /

The part inside the brackets () is a tuple of values to insert into the 
format string. Putting the three together:


target = "Hello %s."
value = "Lisi"
print target % value

=> prints "Hello Lisi."



-- 
Steven


More information about the Tutor mailing list