Some python syntax that I'm not getting

Chris Mellon arkanes at gmail.com
Fri Dec 7 14:14:59 EST 2007


On Dec 7, 2007 6:31 AM, waltbrad <waltbrad at hotmail.com> wrote:
> Hello. Been studying Python for about a week now. I did a quick read
> of the tutorial in the manual and I'm reading Programming Python by
> Mark Lutz.   I'm still getting used to the Python syntax, but I'm able
> to pretty much follow what is being said.  But tonight Lutz was
> talking about implementing a database on a website and threw out this
> piece in his code:
>
> <tr><th>key<td><input type=text name=key value="%(key)s">
>
> That last bit is the bit that throws me: %(keys)s
>
> He explains this so:
>
> "The only feat of semimagic it relies on is using a record's attribute
> dictionary (__dict__) as the source of values when applying string
> formatting to the HTML reply template string in the last line of the
> script. Recall that a %(key)code replacement target fetches a value by
> key from a dictionary:
>
> >>> D = {'say': 5, 'get': 'shrubbery'}
> >>> D['say']
> 5
> >>> S = '%(say)s => %(get)s' % D
> >>> S
> '5 => shrubbery'       "
>
> Hmmmmm...
>
> I understand how D['say'] gets you 5,  But I still don't understand
> the line after the 5.
>
> How is the character 's' some special code?  And I don't get what is
> going on with the % character.  I'm used to it's use in c-style
> formatting, but this just seems so bizarre.  I can tell that the key
> is being replaced by it's value in the string, but I don't know how
> that is being done.
>
> TIA
>

Python string interpolation is based on the C printf style:
"one two %s" % ("three",)

is basically the same as
printf("one two %s", "three")

(% being overload for strings to do formatting).

Used this way, as in C, each wildcard in the format string is replaced
in order with the corresponding item in the format arguments, which is
a sequence.

However, you can also provide a dictionary (that is, a key/value
mapping) to the string formatter, and use the %(key)s format. The name
in the parenthesis is looked up in the provided dictionary, rather
than by position.

This is basically the same thing as the difference between positional
and named arguments.



More information about the Python-list mailing list