Some python syntax that I'm not getting

waltbrad waltbrad at hotmail.com
Fri Dec 7 07:31:03 EST 2007


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




More information about the Python-list mailing list