What does %%(%s)s mean/expand to in Python? What does rowshtml += (rowhtml % ((fieldname, ) * 3)) expand to? Kindly explain.

Peter Otten __peter__ at web.de
Wed Oct 29 08:42:12 CET 2014


satishmlmlml at gmail.com wrote:


> What does %%(%s)s mean in Python?

According to 

https://docs.python.org/2/library/stdtypes.html#string-formatting

in an expression like

"%%(%s)s" % ("foo",)

'%%' expands to '%' and

'%s' expands to 'foo'

so the whole thing gives

>>> "%%(%s)s" % ("foo",)
'%(foo)s'

To this you can then apply another formatting operation that takes a dict as 
its right operand to look up 'foo':

>>> "%(foo)s" % {"foo": "bar"}
'bar'

What you have with "%%(%s)s" is then a template for a template.

> also
> what does
> rowshtml += (rowhtml % ((fieldname,) * 3)) expand to?

(fieldname,)

is a 1-tuple, so

(fieldname,) *3  gives a 3-tuple (fieldname, fieldname, fieldname):

>>> fieldname = "foo"
>>> (fieldname,) * 3
('foo', 'foo', 'foo')

rowhhtml % (fieldname, fieldname, fieldname)

is again string interpolation. Assuming rowhtml contains

"<%s>%s<%s>" may you get

>>> fieldname = "foo"
>>> rowhtml = "<%s>%s</%s>"
>>> rowhtml % ((fieldname,)*3)
'<foo>foo</foo>'





More information about the Python-list mailing list