[Tutor] Defining a "format string"

Noah Hall enalicho at gmail.com
Sun Jun 26 15:53:47 CEST 2011


On Sun, Jun 26, 2011 at 2:42 PM, Lisi <lisi.reisz at gmail.com> wrote:
> Thanks, Noah and Steven.  :-)
>
> On Sunday 26 June 2011 12:24:12 Steven D'Aprano wrote:
>> 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."
>
> At least I had managed to pick up correctly that the format string needed a %
> symbol!
>
> So, if I have now understood correctly, a format string is a string containing
> at least one variable, and the variable(s) is/are preceded by the % symbol.

Well, sort of. Leaning more to the "no" side, but sort of.

A format string is a string containing specifiers (placeholders, if
you will) for values, including variables, but not the values
themselves.

The % symbol is a specifier. So, for example, %d specifies that
something should be of type d which, in Python, is an int.

The actual variables/values are the bit after the format string, and
after the %.

HTH.


More information about the Tutor mailing list