% symbol in python

alex23 wuwei23 at gmail.com
Wed Oct 29 01:25:45 EDT 2014


On 29/10/2014 2:41 PM, satishmlmlml at gmail.com wrote:
 > kindly let me know what is $ROWS$ along with % symbol's meaning

It's a token, a static value added to the template to indicate where 
additional data will be added.

So $ROW$ in this section:

>   <table>
>   <tr><th>key<td><input type=text name=key value="%(key)s">
>   $ROWS$
 >   </table>

Will be replaced by whatever rowshtml contains at this point:

>   replyhtml = replyhtml.replace('$ROWS$', rowshtml)

Of note: the template section above has opening tags for <tr>, <th> and 
<td> but no closing ones. It's not valid html.

Also I don't think this is doing what you think it is:

 > rowhtml = '<tr><th>%s<td><input type=text name=%s value="%%(%s)s">\n'
 > rowshtml = ''
 > for fieldname in fieldnames:
 >  rowshtml += (rowhtml % ((fieldname, ) * 3))
 >  replyhtml = replyhtml.replace('$ROWS$', rowshtml)

After the first fieldname ('name' in this case), the token $ROWS$ will 
be replaced by the string :

     '<tr><th>name<td><input type=text name=name value="%%(name)s">\n'.

On the second iteration of the loop, when fieldname is 'age', rowshtml 
will equal:

      '<tr><th>name<td><input type=text name=name 
value="%%(name)s">\n<tr><th>age<td><input type=text name=age 
value="%%(age)s">\n'

...but nothing will happen with it as $ROWS$ has already been replaced 
during the first time through the loop. Either the `replyhtml = ...` 
line is mis-indented or the code is terribly broken.

Unless this is for homework, I highly recommend just using one of the 
many templating libraries that exist for Python, such as Jinja2.



More information about the Python-list mailing list