variable substitution

Steve Holden sholden at holdenweb.com
Wed Apr 24 09:32:48 EDT 2002


"Hugh" <h.e.w.frater at cs.cf.ac.uk> wrote ...
> How do I get the %(variable)s thing to work. I need to substitute a
> variable into a print statement so I can send links with sessionId's
> attached back to the browser. I'm trying this at the moment, and It
> says invalid sysntax.
> print '<a href = "addItemType.py?sessionID=%(sessionId)s">Add Item
> Type</a>'
> I saw this in a document written by Guido that I found here:
> http://www.w3j.com/6/s3.vanrossum.html
>

You need to add a "%" operator and put a dictionary on its RHS. The
parenthesised words are then used to look up the appropriate values in the
dictionary (technically, any mapping type will work). e.g.:

    print '''<a href = "addItemType.py?sessionID=%(sessionId)s">Add Item
Type</a>''' % {'sessionId': 'XXX1234'}

Of course, it's more useful of the dictionary is reusable, or if you are
substituting more than one value. Otherwise you could just use the shorter
forms, e.g.:

    print '''<a href = "addItemType.py?sessionID=%s">Add Item Type</a>''' %
'XXX1234'

Note that if there is more than one value to substitute, you have to use a
tuple on the RHS, as in

    print '''<a href = "addItemType.py?sessionID=%s">Add %s Item Type</a>'''
% ('XXX1234', 'My')

A few experiments with the interactive interpreter should set you straight.

regards
 Steve
--

home: http://www.holdenweb.com/
Python Web Programming:
http://pydish.holdenweb.com/pwp/








More information about the Python-list mailing list