variable substitution

Noah Spurrier noah at noah.org
Wed Apr 24 10:14:59 EDT 2002


It looks like you are trying to do Perl :-P
You're close, but you need to use a dictionary.
You still must follow the string with a dictonary that
contains the values to be substituted. So it takes the form
    'My string substitution %(my_key_name)s'  %  my_dictionary
The substitutions in the form  %(name)s  are not variable names.
They are key names into the dictionary.

In your case something like this would work:

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

What may have confused you in the examples in the URL you gave
is that the string formats were defined and assigned to variables before
they were used.
In your case it might look like this:

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

    # Stuff happens... Many lines of code later...
    print  format  %  foo

See the end of this section 7.1:

http://www.python.org/doc/current/tut/node9.html#SECTION00910000000000000000
0

Yours,
Noah

----- Original Message -----
From: "Hugh" <h.e.w.frater at cs.cf.ac.uk>
Newsgroups: comp.lang.python
To: <python-list at python.org>
Sent: Wednesday, April 24, 2002 6:19 AM
Subject: variable substitution


> 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
>
>
> hugh
>






More information about the Python-list mailing list