What does % mean/does in this context?

Mike Hjorleifsson mhjorleifsson at gmail.com
Tue Feb 5 23:21:15 EST 2008


At first glance it looks like a replace for _button_cart with the
dictionary items listed in the curly braces
and stuffing them into a list item (cartitems)





On Feb 2, 8:47 am, Tim Chase <python.l... at tim.thechases.com> wrote:
> >   for item in cart.values():
> >             v = _button_cart % {"idx": idx,
> >                                 "itemname": item.name,
> >                                 "amount": item.cost,
> >                                 "quantity": item.quantity,}
> >             cartitems.append(v)
>
> > What does the % operator is doing there?
>
> Unless _button_cart is some funky object with its modulo-operator
> overloaded, _button_cart is likely a string.  For strings, the
> "%" does string formatting.  If the RHS is a dict (in this case),
> it's flexible and allows for named lookups
>
> Thus, _button_cart likely contains something like
>
>   _button_cart = """
>     %(idx)s
>     ========
>     The user bought %(quantity)s %(itemname)s.
>     They cost $%(amount)0.02f"""
>
> You're likely already familiar with the case when the RHS is a
> tuple/list instead of a dict:
>
>  s = "I have %i tests to take on %s" % (
>    test_count, day_of_week)
>
> You can read the nitty-gritty details at
>
> http://docs.python.org/lib/typesseq-strings.html
>
> -tkc




More information about the Python-list mailing list