[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Re: What does % mean/does in this context?

Tim Chase

2/2/2008 1:48:00 PM

> 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-st...

-tkc




1 Answer

Mike Hjorleifsson

2/6/2008 4:21:00 AM

0

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...@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-st...
>
> -tkc