What does % mean/does in this context?

Tim Chase python.list at tim.thechases.com
Sat Feb 2 08:47:55 EST 2008


>   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